#!/usr/bin/env python3
"""AthenaOS command line interface."""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
TEMPLATES_DIR = REPO_ROOT / "templates"
DEFAULT_WORKSPACE = Path(os.environ.get("ATHENA_WORKSPACE", "/workspace/projects"))


CHECKS = {
    "git": ["git", "--version"],
    "python3": ["python3", "--version"],
    "node": ["node", "--version"],
    "npm": ["npm", "--version"],
    "docker": ["docker", "--version"],
    "docker compose": ["docker", "compose", "version"],
}


def run_command(command: list[str]) -> tuple[bool, str]:
    try:
        result = subprocess.run(
            command,
            check=False,
            capture_output=True,
            text=True,
            timeout=8,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
        return False, str(exc)

    output = (result.stdout or result.stderr).strip()
    return result.returncode == 0, output


def doctor(_: argparse.Namespace) -> int:
    print("AthenaOS doctor")
    print("================")

    failed = 0
    for name, command in CHECKS.items():
        ok, output = run_command(command)
        status = "ok" if ok else "missing"
        print(f"{name:14} {status:8} {output}")
        if not ok:
            failed += 1

    print()
    print(f"workspace      {'ok' if DEFAULT_WORKSPACE.exists() else 'missing'}  {DEFAULT_WORKSPACE}")
    return 1 if failed else 0


def copy_template(source: Path, destination: Path) -> None:
    if destination.exists():
        raise FileExistsError(f"{destination} already exists")
    shutil.copytree(source, destination)


def new_project(args: argparse.Namespace) -> int:
    template = args.template.lower()
    source = TEMPLATES_DIR / template
    if not source.is_dir():
        available = ", ".join(sorted(path.name for path in TEMPLATES_DIR.iterdir() if path.is_dir()))
        print(f"Unknown template '{template}'. Available: {available}", file=sys.stderr)
        return 2

    project_name = args.name or template
    destination = Path(args.directory or ".").resolve() / project_name

    try:
        copy_template(source, destination)
    except FileExistsError as exc:
        print(f"Cannot create project: {exc}", file=sys.stderr)
        return 1

    print(f"Created {template} project at {destination}")
    print(f"Next: cd {destination} && docker compose up --build")
    return 0


def banner(_: argparse.Namespace) -> int:
    banner_path = REPO_ROOT / "configs" / "banner.txt"
    print(banner_path.read_text(encoding="utf-8"))
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="athena", description="AthenaOS developer platform CLI")
    subparsers = parser.add_subparsers(dest="command", required=True)

    doctor_parser = subparsers.add_parser("doctor", help="check local development dependencies")
    doctor_parser.set_defaults(func=doctor)

    new_parser = subparsers.add_parser("new", help="create a project from an Athena template")
    new_parser.add_argument("template", help="template name, such as fastapi or nextjs")
    new_parser.add_argument("name", nargs="?", help="project directory name")
    new_parser.add_argument("--directory", "-C", help="parent directory for the generated project")
    new_parser.set_defaults(func=new_project)

    banner_parser = subparsers.add_parser("banner", help="print the AthenaOS banner")
    banner_parser.set_defaults(func=banner)

    args = parser.parse_args(argv)
    return args.func(args)


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

