#!/usr/bin/env python3
"""Simple JSON storage server for Thai vocab game"""
import http.server, json, os, re

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

def read_data(uid):
    path = os.path.join(DATA_DIR, f'{uid}.json')
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return {'wrongWords': [], 'stats': {}}

def write_data(uid, data):
    path = os.path.join(DATA_DIR, f'{uid}.json')
    with open(path, 'w') as f:
        json.dump(data, f, ensure_ascii=False)

class Handler(http.server.BaseHTTPRequestHandler):
    def do_OPTIONS(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')
        self.end_headers()

    def do_GET(self):
        path = self.path
        # Serve static files
        if path.startswith('/api/'):
            uid = path[5:]
            if not uid or not re.match(r'^[a-zA-Z0-9_-]+$', uid):
                self.send_error(400)
                return
            data = read_data(uid)
            self.send_response(200)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(data, ensure_ascii=False).encode())
            return
        # Serve static files from workspace
        fpath = '/home/mi/.openclaw/workspace' + (path if path != '/' else '/thai-vocab.html')
        if os.path.isfile(fpath):
            ct = 'text/html'
            if fpath.endswith('.css'): ct = 'text/css'
            elif fpath.endswith('.js'): ct = 'application/javascript'
            elif fpath.endswith('.json'): ct = 'application/json'
            self.send_response(200)
            self.send_header('Content-Type', ct)
            self.end_headers()
            with open(fpath, 'rb') as f:
                self.wfile.write(f.read())
            return
        self.send_error(404)
        return
    def _old_get(self):
        uid = self.path.strip('/')
        if not uid or not re.match(r'^[a-zA-Z0-9_-]+$', uid):
            self.send_error(400)
            return
        data = read_data(uid)
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data, ensure_ascii=False).encode())

    def do_POST(self):
        path = self.path
        if not path.startswith('/api/'):
            self.send_error(404)
            return
        uid = path[5:]
        if not uid or not re.match(r'^[a-zA-Z0-9_-]+$', uid):
            self.send_error(400)
            return
        length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(length)
        try:
            data = json.loads(body)
        except:
            self.send_error(400)
            return
        write_data(uid, data)
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(b'{"ok":true}')

if __name__ == '__main__':
    httpd = http.server.HTTPServer(('127.0.0.1', 8081), Handler)
    print('Save server on :8081')
    httpd.serve_forever()
