#!/usr/bin/env python3
"""Thai vocab game server - serves static files + JSON storage API"""
import http.server, json, os, re, sys

WORKSPACE = '/home/mi/.openclaw/workspace'
DATA_DIR = os.path.join(WORKSPACE, 'game_data')
os.makedirs(DATA_DIR, exist_ok=True)

class Handler(http.server.BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_cors()
        self.end_headers()

    def send_cors(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')

    def send_json(self, data, status=200):
        self.send_response(status)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.end_headers()
        self.wfile.write(json.dumps(data, ensure_ascii=False).encode())

    def do_GET(self):
        path = self.path
        # API: /api/<uid>  
        if path.startswith('/api/'):
            uid = path[5:].strip()
            if not uid or not re.match(r'^[\w-]+$', uid):
                return self.send_json({'error': 'invalid uid'}, 400)
            fpath = os.path.join(DATA_DIR, f'{uid}.json')
            if os.path.exists(fpath):
                with open(fpath) as f:
                    data = json.load(f)
                return self.send_json(data)
            return self.send_json({'wrongWords': [], 'stats': {}})
        
        # Serve static files
        if path == '/' or path == '':
            path = '/thai-vocab.html'
        fpath = os.path.join(WORKSPACE, path.lstrip('/'))
        if not os.path.isfile(fpath):
            return self.send_json({'error': 'not found'}, 404)
        
        ext = os.path.splitext(fpath)[1]
        ctype = {'html': 'text/html', 'css': 'text/css', 'js': 'application/javascript', 'json': 'application/json'}.get(ext.lstrip('.'), 'text/plain')
        self.send_response(200)
        self.send_header('Content-Type', f'{ctype}; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        with open(fpath, 'rb') as f:
            self.wfile.write(f.read())

    def do_POST(self):
        if not self.path.startswith('/api/'):
            return self.send_json({'error': 'not found'}, 404)
        uid = self.path[5:].strip()
        if not uid or not re.match(r'^[\w-]+$', uid):
            return self.send_json({'error': 'invalid uid'}, 400)
        
        cl = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(cl) if cl > 0 else b'{}'
        try:
            data = json.loads(body)
        except:
            return self.send_json({'error': 'invalid json'}, 400)
        
        fpath = os.path.join(DATA_DIR, f'{uid}.json')
        with open(fpath, 'w') as f:
            json.dump(data, f, ensure_ascii=False)
        self.send_json({'ok': True})

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
    httpd = http.server.HTTPServer(('127.0.0.1', port), Handler)
    print(f'Thai game server on :{port}')
    httpd.serve_forever()
