from __future__ import annotations

import html
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs

from ..config import ConfigManager


def _parse_ids(raw: str) -> list[int]:
    result = []
    for chunk in raw.replace("\n", ",").split(","):
        item = chunk.strip()
        if item and item.lstrip("-").isdigit():
            result.append(int(item))
    return result


def render_settings_page(config: dict, *, notice: str = "") -> str:
    telegram = config.get("telegram", {}) or {}
    providers = (config.get("providers", {}) or {}).get("items", {}) or {}
    openai = providers.get("openai", {}) or {}
    gemini = providers.get("gemini", {}) or {}
    openrouter = providers.get("openrouter", {}) or {}
    notice_html = f"<p style='color: green'>{html.escape(notice)}</p>" if notice else ""
    return f"""<!doctype html>
<html>
<head>
  <meta charset='utf-8'>
  <title>OpenClaw Lite Settings</title>
  <style>
    body {{ font-family: sans-serif; max-width: 840px; margin: 24px auto; padding: 0 16px; }}
    label {{ display:block; margin-top: 12px; font-weight: 600; }}
    input, textarea {{ width: 100%; padding: 8px; margin-top: 4px; box-sizing: border-box; }}
    button {{ margin-top: 16px; padding: 10px 14px; }}
    .hint {{ color: #666; font-size: 12px; }}
  </style>
</head>
<body>
  <h1>OpenClaw Lite Settings</h1>
  {notice_html}
  <form method='post' action='/save'>
    <label>Telegram Bot Token
      <input type='text' name='telegram_bot_token' value='{html.escape(str(telegram.get("bot_token", "")))}'>
    </label>
    <label>Owner User IDs
      <input type='text' name='telegram_owner_user_ids' value='{html.escape(",".join(str(x) for x in telegram.get("owner_user_ids", [])))}'>
      <div class='hint'>Comma-separated Telegram user ids.</div>
    </label>
    <label>Allowed User IDs
      <input type='text' name='telegram_allowed_user_ids' value='{html.escape(",".join(str(x) for x in telegram.get("allowed_user_ids", [])))}'>
    </label>
    <label>Allowed Chat IDs
      <input type='text' name='telegram_allowed_chat_ids' value='{html.escape(",".join(str(x) for x in telegram.get("allowed_chat_ids", [])))}'>
    </label>
    <label>OpenAI API Key
      <input type='text' name='openai_api_key' value='{html.escape(str(openai.get("api_key", "")))}'>
    </label>
    <label>OpenAI Default Model
      <input type='text' name='openai_default_model' value='{html.escape(str(openai.get("default_model", "")))}'>
    </label>
    <label>Gemini API Key
      <input type='text' name='gemini_api_key' value='{html.escape(str(gemini.get("api_key", "")))}'>
    </label>
    <label>Gemini Default Model
      <input type='text' name='gemini_default_model' value='{html.escape(str(gemini.get("default_model", "")))}'>
    </label>
    <label>OpenRouter API Key
      <input type='text' name='openrouter_api_key' value='{html.escape(str(openrouter.get("api_key", "")))}'>
    </label>
    <label>OpenRouter Base URL
      <input type='text' name='openrouter_base_url' value='{html.escape(str(openrouter.get("base_url", "")))}'>
    </label>
    <button type='submit'>Save settings</button>
  </form>
</body>
</html>"""


def update_config_from_form(manager: ConfigManager, form: dict[str, str]) -> dict:
    manager.backup("web-ui")
    data = manager.data
    telegram = data.setdefault("telegram", {})
    telegram["bot_token"] = form.get("telegram_bot_token", "")
    telegram["owner_user_ids"] = _parse_ids(form.get("telegram_owner_user_ids", ""))
    telegram["allowed_user_ids"] = _parse_ids(form.get("telegram_allowed_user_ids", ""))
    telegram["allowed_chat_ids"] = _parse_ids(form.get("telegram_allowed_chat_ids", ""))

    providers = data.setdefault("providers", {}).setdefault("items", {})
    providers.setdefault("openai", {})["api_key"] = form.get("openai_api_key", "")
    providers.setdefault("openai", {})["default_model"] = form.get("openai_default_model", "")
    providers.setdefault("gemini", {})["api_key"] = form.get("gemini_api_key", "")
    providers.setdefault("gemini", {})["default_model"] = form.get("gemini_default_model", "")
    providers.setdefault("openrouter", {})["api_key"] = form.get("openrouter_api_key", "")
    providers.setdefault("openrouter", {})["base_url"] = form.get("openrouter_base_url", "")

    manager.save()
    return manager.data


def run_web_ui(config_path: str, host: str = "127.0.0.1", port: int = 8787) -> None:
    manager = ConfigManager(config_path)

    class Handler(BaseHTTPRequestHandler):
        def _send_html(self, body: str, status: int = 200) -> None:
            data = body.encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self) -> None:
            if self.path not in {"/", "/index.html"}:
                self._send_html("<h1>Not Found</h1>", 404)
                return
            manager.reload()
            self._send_html(render_settings_page(manager.data))

        def do_POST(self) -> None:
            if self.path != "/save":
                self._send_html("<h1>Not Found</h1>", 404)
                return
            length = int(self.headers.get("Content-Length", "0"))
            raw = self.rfile.read(length).decode("utf-8")
            parsed = {key: values[-1] for key, values in parse_qs(raw, keep_blank_values=True).items()}
            update_config_from_form(manager, parsed)
            self._send_html(render_settings_page(manager.data, notice="Saved. Use /reload in Telegram or restart runtime."))

        def log_message(self, format, *args):
            return

    server = ThreadingHTTPServer((host, port), Handler)
    try:
        print(f"OpenClaw Lite web UI: http://{host}:{port}")
        server.serve_forever()
    finally:
        server.server_close()
