"""在本机打开 site 里的网页，并只读提供最近五局成绩。"""
import json
from configparser import Error as ConfigError
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
from mysql.connector import Error as DatabaseError
from score_store import connect

ROOT = Path(__file__).resolve().parent


class ResultsHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        if urlsplit(self.path).path != "/scores.json":
            return super().do_GET()
        try:
            with connect() as db, db.cursor(dictionary=True) as cursor:
                db.start_transaction(readonly=True)
                cursor.execute("""
                    SELECT p.nickname, r.score, r.played_at FROM rounds AS r
                    JOIN players AS p ON p.id = r.player_id
                    ORDER BY r.played_at DESC, r.id DESC LIMIT 5
                """)
                result = cursor.fetchall()
            for row in result:
                row["played_at"] = row["played_at"].isoformat()
        except (DatabaseError, ConfigError, OSError, ValueError):
            self.send_json(503, {"message": "请先启动 MySQL，并核对 mysql.local.ini 中的连接和库名。"})
        else:
            self.send_json(200, result)

    def send_json(self, status, result):
        data = json.dumps(result, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


if __name__ == "__main__":
    if not (ROOT / "site" / "index.html").is_file():
        raise SystemExit("请把自己的 site 文件夹放到本程序旁边，并确认其中有 index.html。")
    handler = partial(ResultsHandler, directory=str(ROOT / "site"))
    with ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
        print(f"打开 http://127.0.0.1:{server.server_port}/ ，结束时按 Ctrl+C。", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass
