"""GodotIQ CLI — argument parsing and subcommand dispatch."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path


def cli_main() -> None:
    """Parse arguments and dispatch to the appropriate handler."""
    from godotiq import __version__

    parser = argparse.ArgumentParser(
        prog="godotiq",
        description="GodotIQ — The definitive MCP for AI-assisted Godot development.",
    )
    parser.add_argument(
        "--version", action="version", version=f"godotiq {__version__}"
    )

    subparsers = parser.add_subparsers(dest="command")

    install_parser = subparsers.add_parser(
        "install-addon", help="Copy GodotIQ addon files to a Godot project"
    )
    install_parser.add_argument("path", help="Path to Godot project root")
    install_parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Preview what would be copied without writing files",
    )

    args = parser.parse_args()

    if args.command is None:
        _serve()
    elif args.command == "install-addon":
        install_addon(args.path, dry_run=args.dry_run)
    else:
        parser.print_help()
        sys.exit(1)


def _serve() -> None:
    """Start the MCP server (lazy import to avoid loading all tools for other subcommands)."""
    from godotiq.server import main

    main()


_ADDON_EXTENSIONS = {".gd", ".cfg"}


def install_addon(target_dir: str, dry_run: bool = False) -> None:
    """Copy addon files and GODOTIQ_RULES.md to a Godot project."""
    import shutil

    target = Path(target_dir).expanduser().resolve()
    if not target.is_dir():
        print(f"Error: directory does not exist: {target}", file=sys.stderr)
        sys.exit(1)
    if not (target / "project.godot").exists():
        print(
            f"Error: {target} does not appear to be a Godot project (no project.godot found)",
            file=sys.stderr,
        )
        sys.exit(1)

    # Locate source files
    pkg_dir = Path(__file__).resolve().parent
    addon_src = pkg_dir / "addon"
    rules_src = pkg_dir / "prompts" / "godot_development.md"

    # In editable installs, force-include files aren't in addon/.
    # Fall back to the repo's godot-addon/ directory.
    has_addon_files = (
        addon_src.is_dir()
        and any(f.suffix in _ADDON_EXTENSIONS for f in addon_src.iterdir() if f.is_file())
    )
    if not has_addon_files:
        repo_addon = pkg_dir.parent.parent / "godot-addon" / "addons" / "godotiq"
        if repo_addon.is_dir():
            addon_src = repo_addon

    # Build copy manifest: (source, destination, relative_display_path)
    manifest: list[tuple[Path, Path, str]] = []

    for f in sorted(addon_src.iterdir()):
        if f.suffix in _ADDON_EXTENSIONS:
            dst = target / "addons" / "godotiq" / f.name
            manifest.append((f, dst, f"addons/godotiq/{f.name}"))

    if not manifest:
        print("Error: could not locate addon source files.", file=sys.stderr)
        sys.exit(1)

    if rules_src.exists():
        manifest.append((rules_src, target / "GODOTIQ_RULES.md", "GODOTIQ_RULES.md"))

    # Dry-run mode
    if dry_run:
        print(f"[dry-run] Would install GodotIQ addon to {target}")
        for _, _, rel in manifest:
            print(f"  would copy: {rel}")
        return

    # Create destination directory
    (target / "addons" / "godotiq").mkdir(parents=True, exist_ok=True)

    # Copy files and report
    print(f"Installing GodotIQ addon to {target} ...")
    added = 0
    updated = 0
    for src, dst, rel in manifest:
        existed = dst.exists()
        shutil.copy2(src, dst)
        status = "updated" if existed else "added"
        if existed:
            updated += 1
        else:
            added += 1
        print(f"  {status:>9s}: {rel}")

    print(f"\nDone. {added} files added, {updated} files updated.")
