"""CLI for BURN-E — release and CI/CD management."""

from __future__ import annotations

import argparse
import json


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="axi release",
        description="BURN-E — build, test, tag, and publish releases",
    )
    sub = parser.add_subparsers(dest="action")

    sub.add_parser("status", help="Show build and release status")
    sub.add_parser("mode", help="Show developer vs operator mode")
    sub.add_parser("patterns", help="Show known CI failure patterns")
    sub.add_parser("check", help="Run pre-push prevention checks")

    plan_p = sub.add_parser("plan", help="Show release plan")
    plan_p.add_argument("--format", choices=["human", "json"], default="human")

    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    if not args.action:
        parser.print_help()
        return 1

    handlers = {
        "status": _cmd_status,
        "mode": _cmd_mode,
        "patterns": _cmd_patterns,
        "check": _cmd_check,
        "plan": _cmd_plan,
    }
    return handlers[args.action](args)


def _cmd_status(args: argparse.Namespace) -> int:
    from .ci_monitor import get_build_status

    status = get_build_status()

    print("BURN-E Build Status")
    print("=" * 50)
    print(f"Mode: {status['mode']['mode']}")
    print()

    for p in status["pipelines"]:
        icon = (
            "pass"
            if p["status"] == "success"
            else "FAIL"
            if p["status"] in ("failed", "failure")
            else "..."
        )
        print(f"  [{icon}] {p['repo']:<15} {p['ref']:<10} {p['status']}")

    if not status["pipelines"]:
        print("  No pipelines detected. Configure gh CLI and/or GITLAB_TOKEN.")

    print()
    if status["all_green"]:
        print("All green. Ready to release.")
    else:
        print("Build issues detected. Run `axi release check` for diagnostics.")

    return 0


def _cmd_mode(args: argparse.Namespace) -> int:
    from .mode import detect_mode

    mode = detect_mode()
    d = mode.to_dict()

    print(f"Mode: {d['mode']}")
    print("\nAxiom (axi-platform):")
    print(f"  Version:  {d['axiom']['version']}")
    print(f"  Source:   {d['axiom']['source']}")
    print(f"  Editable: {d['axiom']['editable']}")
    print("\nNeutronOS (neutron-os):")
    print(f"  Version:  {d['neutronos']['version']}")
    print(f"  Source:   {d['neutronos']['source']}")
    print(f"  Editable: {d['neutronos']['editable']}")

    return 0


def _cmd_patterns(args: argparse.Namespace) -> int:
    from .failure_patterns import FailurePatternDB

    db = FailurePatternDB()
    patterns = db.load()

    print(f"Known CI Failure Patterns ({len(patterns)}):\n")
    for p in patterns:
        print(f"  [{p.source}] {p.name}")
        print(f"    Diagnosis: {p.diagnosis}")
        print(f"    Fix: {p.fix}")
        if p.occurrences:
            print(f"    Seen: {p.occurrences} time(s), last: {p.last_seen[:10]}")
        print()

    return 0


def _cmd_check(args: argparse.Namespace) -> int:
    from .failure_patterns import FailurePatternDB

    db = FailurePatternDB()
    checks = db.get_prevention_checks()

    print(f"Running {len(checks)} prevention checks...\n")

    import subprocess

    failed = 0
    for cmd in checks:
        try:
            result = subprocess.run(
                cmd,
                shell=True,  # noqa: S602
                capture_output=True,
                text=True,
                timeout=30,
                check=False,
            )
            if result.returncode == 0 and result.stdout.strip():
                print(f"  [warn] {cmd}")
                print(f"         {result.stdout.strip()[:100]}")
                failed += 1
            else:
                print(f"  [ok]   {cmd}")
        except Exception as e:
            print(f"  [warn] {cmd}: {e}")

    print(f"\n{len(checks) - failed}/{len(checks)} checks passed.")
    return 0 if failed == 0 else 1


def _cmd_plan(args: argparse.Namespace) -> int:
    from axiom.federation.release_plan import ReleasePlanService

    svc = ReleasePlanService()
    milestones = svc.list_milestones()

    if getattr(args, "format", "human") == "json":
        print(json.dumps([m.to_dict() for m in milestones], indent=2))
    elif not milestones:
        print("No release milestones. Run `axi release plan --add <version>` to create one.")
    else:
        print("Release Plan:\n")
        for m in milestones:
            status_label = {"planned": "PLAN", "tagged": "TAG", "announced": "ANN"}.get(
                m.status, "?"
            )
            tests = sum(f.test_count for f in m.features)
            print(f'  [{status_label}] v{m.version} "{m.codename}"')
            print(f"    Target: {m.target_date}  Status: {m.status}  Tests: {tests}")
            for f in m.features:
                print(f"      - {f.name} ({f.test_count} tests)")
            print()

    return 0
