from __future__ import annotations

import argparse
import json
import platform
import sys
from pathlib import Path

from . import __version__

ENTRY_KEY = "sector8-guard"
ROOT_MARKERS = (".claude", ".git", "pyproject.toml", "package.json")


def find_project_root(start: Path) -> Path | None:
    current = start.resolve()
    for _ in range(10):
        if any((current / marker).exists() for marker in ROOT_MARKERS):
            return current
        if current.parent == current:
            break
        current = current.parent
    return None


def build_entry(project_root: Path) -> dict[str, object]:
    cmd_wrapper = project_root / "scripts" / "run_sector8_guard_mcp.cmd"
    if platform.system() == "Windows" and cmd_wrapper.exists():
        cmd_str = str(cmd_wrapper.relative_to(project_root)).replace("/", "\\")
        return {
            "command": cmd_str,
            "args": [],
            "env": {
                "SECTOR8_API_KEY": "${SECTOR8_API_KEY}",
                "SECTOR8_CLIENT_ID": "${SECTOR8_CLIENT_ID}",
            },
        }

    script = project_root / "sector8-backend" / "scripts" / "mcp_stdio_server.py"
    relative_script = script.relative_to(project_root)
    separator = "\\" if platform.system() == "Windows" else "/"
    script_arg = str(relative_script).replace("/", separator)
    return {
        "command": "python",
        "args": [script_arg],
        "env": {
            "SECTOR8_API_KEY": "${SECTOR8_API_KEY}",
            "SECTOR8_CLIENT_ID": "${SECTOR8_CLIENT_ID}",
        },
    }


def _load_settings(settings_path: Path) -> dict[str, object]:
    if not settings_path.exists():
        return {}
    try:
        return json.loads(settings_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        backup_path = settings_path.with_suffix(".json.bak")
        settings_path.rename(backup_path)
        print(f"Warning: {settings_path} is not valid JSON. Backup created at {backup_path}.")
        return {}


def cmd_install() -> int:
    root = find_project_root(Path.cwd())
    if root is None:
        reply = input("Could not find project root. Install in current directory? [y/N] ")
        if reply.strip().lower() != "y":
            return 0
        root = Path.cwd()

    claude_dir = root / ".claude"
    claude_dir.mkdir(exist_ok=True)
    settings_path = claude_dir / "settings.json"
    settings = _load_settings(settings_path)
    mcp_servers = settings.setdefault("mcpServers", {})

    if not isinstance(mcp_servers, dict):
        mcp_servers = {}
        settings["mcpServers"] = mcp_servers

    existing = mcp_servers.get(ENTRY_KEY)
    if existing is not None:
        existing_policy = None
        if isinstance(existing, dict):
            env_block = existing.get("env")
            if isinstance(env_block, dict):
                existing_policy = env_block.get("ADMISSION_POLICY_VERSION_ID")
        if existing_policy:
            print(f"sector8-guard already installed (policy: {existing_policy})")
        else:
            print("sector8-guard already installed")
        reply = input("Overwrite? [y/N] ")
        if reply.strip().lower() != "y":
            return 0

    mcp_servers[ENTRY_KEY] = build_entry(root)
    settings_path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")

    print(f"\u2713 sector8-guard installed at {settings_path}")
    print("\u2192 Open Claude Code and run /mcp to verify the connection.")
    print("\u2192 SECTOR8_API_KEY and SECTOR8_CLIENT_ID must be set in your environment.")
    return 0


def cmd_version() -> int:
    print(f"sector8-sdk {__version__}")
    return 0


def cmd_verify() -> int:
    print("verify is not implemented yet.")
    return 0


def cmd_uninstall() -> int:
    print("uninstall is not implemented yet.")
    return 0


def guard_main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    command = args[0] if args else "install"

    if command == "install":
        return cmd_install()
    if command == "version":
        return cmd_version()
    if command == "verify":
        return cmd_verify()
    if command == "uninstall":
        return cmd_uninstall()

    print(f"Unknown command: {command}")
    print("Usage: sector8-guard [install|verify|uninstall|version]")
    return 1


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="sector8")
    parser.add_argument("command", nargs="?", default="help")
    parsed = parser.parse_args(argv)

    if parsed.command in {"help", "--help"}:
        parser.print_help()
        return 0
    if parsed.command == "version":
        return cmd_version()

    print(f"Command '{parsed.command}' is not implemented in this SDK build.")
    return 1


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