#!/usr/bin/env python3
"""Write project-root .env from docker/.env for host uvicorn (127.0.0.1 MySQL/Redis)."""

from __future__ import annotations

import sys
from pathlib import Path
from urllib.parse import quote_plus

ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from server.utils.text_io import read_utf8_lf, write_utf8_lf
DOCKER_ENV = ROOT / "docker" / ".env"
OUT = ROOT / ".env"


def _parse(path: Path) -> dict[str, str]:
    data: dict[str, str] = {}
    for line in read_utf8_lf(path).splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        data[key.strip()] = value.strip()
    return data


def main() -> None:
    if not DOCKER_ENV.exists():
        raise SystemExit(f"Missing {DOCKER_ENV} — run: python3 docker/generate_env.py")

    d = _parse(DOCKER_ENV)
    mysql_pass = d.get("MYSQL_PASSWORD", "")
    if not mysql_pass:
        raise SystemExit("MYSQL_PASSWORD missing in docker/.env")

    for key in ("NEXUS_SECRET_KEY", "NEXUS_API_KEY", "NEXUS_ENCRYPTION_KEY"):
        if not d.get(key):
            raise SystemExit(f"{key} missing in docker/.env — run generate_env.py")

    db_user = "nexus"
    db_pass_q = quote_plus(mysql_pass)
    deploy = str(ROOT)
    cors = d.get("NEXUS_CORS_ORIGINS", "http://localhost:8600,http://127.0.0.1:8600")
    api_base = d.get("NEXUS_API_BASE_URL", "http://localhost:8600")

    lines = [
        "# Nexus .env — host uvicorn dev (from docker/sync_root_env.py)",
        "",
        "NEXUS_HOST=0.0.0.0",
        "NEXUS_PORT=8600",
        f"NEXUS_DEPLOY_PATH={deploy}",
        f"NEXUS_CORS_ORIGINS={cors}",
        f"NEXUS_API_BASE_URL={api_base}",
        "",
        f"NEXUS_DATABASE_URL=mysql+aiomysql://{db_user}:{db_pass_q}@127.0.0.1:3306/nexus",
        "NEXUS_DB_POOL_SIZE=20",
        "NEXUS_DB_MAX_OVERFLOW=10",
        "",
        f"NEXUS_SECRET_KEY={d['NEXUS_SECRET_KEY']}",
        f"NEXUS_API_KEY={d['NEXUS_API_KEY']}",
        f"NEXUS_ENCRYPTION_KEY={d['NEXUS_ENCRYPTION_KEY']}",
        "",
        "NEXUS_REDIS_URL=redis://127.0.0.1:6379/0",
        "NEXUS_SSH_STRICT_HOST_CHECKING=false",
        "",
        "# MySQL MCP (optional): python3 scripts/sync_mysql_mcp_env.py",
        "MYSQL_HOST=127.0.0.1",
        "MYSQL_PORT=3306",
        f"MYSQL_USER={db_user}",
        f"MYSQL_PASSWORD={mysql_pass}",
        "MYSQL_DATABASE=nexus",
        "MYSQL_READONLY=false",
        "MYSQL_DATABASE_ALLOWLIST=nexus",
    ]

    write_utf8_lf(OUT, "\n".join(lines) + "\n")
    OUT.chmod(0o600)
    print(f"Wrote {OUT}")


if __name__ == "__main__":
    main()
