from __future__ import annotations

import argparse
from pathlib import Path

from trae_workspace_tool.generator import inspect_workspace, install_workspace
from trae_workspace_tool.registry import (
    DEFAULT_PACK,
    DEFAULT_PROFILE,
    RegistryError,
    list_packs,
    list_profiles,
)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Generate Trae IDE enterprise workspace assets")
    subparsers = parser.add_subparsers(dest="command", required=True)

    init_parser = subparsers.add_parser(
        "init", help="Install Trae profile and pack workspace assets"
    )
    init_parser.add_argument("--target", required=True, help="Target project directory")
    init_parser.add_argument(
        "--profile",
        default=DEFAULT_PROFILE,
        help=f"Workspace profile to install (default: {DEFAULT_PROFILE})",
    )
    init_parser.add_argument(
        "--pack",
        default=DEFAULT_PACK,
        help=f"Workspace pack to install (default: {DEFAULT_PACK})",
    )
    init_parser.add_argument(
        "--force", action="store_true", help="Overwrite existing generated files"
    )

    doctor_parser = subparsers.add_parser("doctor", help="Check generated workspace assets")
    doctor_parser.add_argument("--target", required=True, help="Target project directory")
    doctor_parser.add_argument(
        "--profile",
        default=DEFAULT_PROFILE,
        help=f"Workspace profile to inspect (default: {DEFAULT_PROFILE})",
    )
    doctor_parser.add_argument(
        "--pack",
        default=DEFAULT_PACK,
        help=f"Workspace pack to inspect (default: {DEFAULT_PACK})",
    )

    subparsers.add_parser("list-packs", help="List available workspace packs")
    subparsers.add_parser("list-profiles", help="List available workspace profiles")

    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    try:
        if args.command == "init":
            result = install_workspace(
                Path(args.target),
                force=args.force,
                profile=args.profile,
                pack=args.pack,
            )
            for item in result.created:
                print(f"created: {item}")
            for item in result.overwritten:
                print(f"overwritten: {item}")
            for item in result.skipped:
                print(f"skipped: {item}")
            return 0

        if args.command == "doctor":
            report = inspect_workspace(Path(args.target), profile=args.profile, pack=args.pack)
            for item in report.present:
                print(f"present: {item}")
            for item in report.missing:
                print(f"missing: {item}")
            for item in report.invalid:
                print(f"invalid: {item.relative_path}: {item.reason}")
            return 0 if report.ok else 1

        if args.command == "list-packs":
            for pack in list_packs():
                print(f"{pack.name}: {pack.description}")
            return 0

        if args.command == "list-profiles":
            for profile in list_profiles():
                print(f"{profile.name}: {profile.description}")
            return 0
    except (OSError, RegistryError) as exc:
        parser.exit(1, f"error: {exc}\n")

    parser.error(f"unknown command: {args.command}")
    return 2


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