"""Serve the legacy decompose demo from repo-local files.

The legacy `web/index.html` expects assets at root paths such as
`/frameworks.json`, `/payloads.json`, `/prompt-read/...`, and `/data/...`.
This tiny server preserves those paths without changing the old frontend.
"""
from __future__ import annotations

import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlparse


ROOT = Path(__file__).resolve().parent.parent
WEB = ROOT / "web"
PROMPTS = ROOT / "prompts"
SKILL_EXTRACTION = ROOT / "创作知识提取-skill" / "extraction"


def _load_env_file(path: str | Path) -> dict[str, str]:
    p = Path(path)
    if not p.is_absolute():
        p = ROOT / p
    if not p.exists():
        return {}
    out: dict[str, str] = {}
    for line in p.read_text(encoding="utf-8").splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            continue
        key, value = stripped.split("=", 1)
        out[key.strip()] = value.strip().strip('"').strip("'")
    return out


def _data_root() -> Path:
    env = _load_env_file(os.getenv("CK_ENV_FILE", ".env"))
    raw = os.getenv("CK_DATA_DIR") or env.get("CK_DATA_DIR")
    if not raw:
        raw = "legacy_data" if (ROOT / "legacy_data").exists() else "data"
    p = Path(raw)
    return p if p.is_absolute() else ROOT / p


class LegacyDemoHandler(SimpleHTTPRequestHandler):
    def translate_path(self, path: str) -> str:
        parsed = urlparse(path)
        clean = unquote(parsed.path)
        if clean in {"", "/"}:
            return str(WEB / "index.html")
        if clean.startswith("/data/"):
            return str(_data_root() / clean.removeprefix("/data/"))
        if clean.startswith("/runs/"):
            return str(WEB / clean.lstrip("/"))
        if clean.startswith("/prompt-read/"):
            return str(PROMPTS / clean.removeprefix("/prompt-read/"))
        if clean.startswith("/prompt-skill/"):
            return str(SKILL_EXTRACTION / clean.removeprefix("/prompt-skill/"))
        return str(WEB / clean.lstrip("/"))


def main() -> None:
    server = ThreadingHTTPServer(("127.0.0.1", 8127), LegacyDemoHandler)
    print("Serving legacy demo at http://127.0.0.1:8127/")
    server.serve_forever()


if __name__ == "__main__":
    main()
