import json
import os
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


GATEWAY_BASE = "https://omlx.hellotaiji.com/v1"


def hermes_home() -> Path:
    return Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")


def read_env() -> dict[str, str]:
    env_path = hermes_home() / ".env"
    values: dict[str, str] = {}
    if not env_path.exists():
      return values
    for line in env_path.read_text(encoding="utf-8-sig", errors="ignore").splitlines():
        if not line or line.lstrip().startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        values[key.strip()] = value.strip()
    return values


def call_gateway(api_key: str, model: str, messages: list[dict[str, str]]) -> str:
    payload = {
        "model": model,
        "messages": messages,
        "stream": False,
        "max_tokens": 1024,
    }
    req = Request(
        GATEWAY_BASE + "/chat/completions",
        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
        headers={
            "Authorization": "Bearer " + api_key,
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "Mozilla/5.0 TongchengHermesStudentChat/1.0",
        },
        method="POST",
    )
    try:
        with urlopen(req, timeout=120) as resp:
            data = json.loads(resp.read().decode("utf-8", errors="replace"))
    except HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP {exc.code}: {body[:800]}") from exc
    except URLError as exc:
        raise RuntimeError(f"Network error: {exc.reason}") from exc

    choices = data.get("choices") or []
    if not choices:
        return ""
    message = choices[0].get("message") or {}
    return str(message.get("content") or "")


def main() -> int:
    env = read_env()
    api_key = env.get("TONGCHENG_GATEWAY_API_KEY", "") or env.get("OPENAI_API_KEY", "")
    model = env.get("HERMES_INFERENCE_MODEL", "tc-main") or "tc-main"
    if not api_key.startswith("sk-tc_"):
        print("API Key is missing. Please run 02_CONFIGURE_KEY.cmd first.")
        return 1

    print("Tongcheng Hermes Student Chat")
    print("Type /exit to quit. Type /clear to start a new chat.")
    print("")
    messages: list[dict[str, str]] = [
        {
            "role": "system",
            "content": "你是童澄 AI 学习助手。请用清晰、友好、适合学生理解的中文回答。不要声称可以执行本地命令或读取本地文件。",
        }
    ]
    while True:
        try:
            prompt = input("> ").strip()
        except (EOFError, KeyboardInterrupt):
            print("")
            return 0
        if not prompt:
            continue
        if prompt.lower() in {"/exit", "exit", "quit", "q"}:
            return 0
        if prompt.lower() == "/clear":
            messages = messages[:1]
            print("Chat cleared.")
            continue
        messages.append({"role": "user", "content": prompt})
        try:
            answer = call_gateway(api_key, model, messages)
        except Exception as exc:
            print("")
            print("Error:", exc)
            print("")
            messages.pop()
            continue
        print("")
        print(answer or "(empty response)")
        print("")
        messages.append({"role": "assistant", "content": answer})


if __name__ == "__main__":
    raise SystemExit(main())
