#!/usr/bin/env python3

import os
import subprocess
import sys
from pathlib import Path


def load_dotenv(path: Path) -> dict[str, str]:
    env: dict[str, str] = {}

    if not path.exists():
        return env

    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue

        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip()

        if value and value[0] == "'" and value.endswith("'"):
            value = value[1:-1]
        elif value and value[0] == '"' and value.endswith('"'):
            value = value[1:-1]

        env[key] = value

    return env


def main() -> int:
    repo_root = Path(__file__).resolve().parents[1]
    dotenv_path = repo_root / ".env"

    dotenv = load_dotenv(dotenv_path)

    required = ["GITEA_HOST", "GITEA_ACCESS_TOKEN"]
    missing = [k for k in required if not dotenv.get(k)]
    if missing:
        sys.stderr.write(
            "Missing required env vars in .env: " + ", ".join(missing) + "\n"
        )
        return 2

    env = os.environ.copy()

    # Prefer values from .env to keep VS Code config simple.
    for key in [
        "GITEA_HOST",
        "GITEA_ACCESS_TOKEN",
        "GITEA_DEBUG",
        "GITEA_READONLY",
        "GITEA_INSECURE",
    ]:
        if key in dotenv:
            env[key] = dotenv[key]

    cmd = [
        "docker",
        "run",
        "-i",
        "--rm",
        "-e",
        "GITEA_HOST",
        "-e",
        "GITEA_ACCESS_TOKEN",
    ]

    # Optional flags.
    for optional in ["GITEA_DEBUG", "GITEA_READONLY", "GITEA_INSECURE"]:
        if env.get(optional):
            cmd.extend(["-e", optional])

    cmd.append("docker.gitea.com/gitea-mcp-server:latest")

    # Inherit stdin/stdout/stderr for MCP stdio.
    completed = subprocess.run(cmd, env=env, check=False)
    return int(completed.returncode)


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