"""
nokrashi CLI - Run code quality checks from the command line.

Usage:
    nokrashi run --project-root .
    nokrashi run --project-root . --dashboard-uid abc123 --grafana-url https://grafana.example.com
    nokrashi analyze --project-root /path/to/project
"""

import argparse
import json
import sys
from pathlib import Path


def cmd_run(args: argparse.Namespace) -> int:
    """Run standards tests (TestSuite checks)."""
    from . import TestSuite

    project_root = Path(args.project_root).resolve()
    if not project_root.exists():
        print(f"Error: project root does not exist: {project_root}", file=sys.stderr)
        return 1

    suite = TestSuite(
        project_root=project_root,
        grafana_dashboard_uid=args.dashboard_uid or "",
        grafana_url=args.grafana_url,
        grafana_metrics_interval=args.metrics_interval,
        grafana_api_token=args.grafana_token,
    )

    TestClass = suite.create_test_class()
    instance = TestClass()

    # Collect all test methods
    test_methods = [m for m in dir(instance) if m.startswith("test_")]
    passed = 0
    failed = 0
    skipped = 0
    errors = []

    for method_name in sorted(test_methods):
        if method_name in suite.skip_tests:
            skipped += 1
            continue

        try:
            getattr(instance, method_name)()
            passed += 1
            if args.verbose:
                print(f"  PASS  {method_name}")
        except AssertionError as e:
            failed += 1
            errors.append((method_name, str(e)))
            if args.verbose:
                print(f"  FAIL  {method_name}")
                for line in str(e).split("\n")[:3]:
                    print(f"        {line}")
        except Exception as e:
            skipped += 1
            if args.verbose:
                print(f"  SKIP  {method_name} ({e})")

    # Summary
    print(f"\n{passed} passed, {failed} failed, {skipped} skipped")

    if errors and not args.verbose:
        print("\nFailures:")
        for name, msg in errors:
            print(f"  {name}:")
            for line in msg.split("\n")[:3]:
                print(f"    {line}")

    return 1 if failed > 0 else 0


def cmd_analyze(args: argparse.Namespace) -> int:
    """Run project analysis."""
    from . import AnalysisConfig, analyze_project

    project_root = Path(args.project_root).resolve()
    if not project_root.exists():
        print(f"Error: project root does not exist: {project_root}", file=sys.stderr)
        return 1

    config = AnalysisConfig(
        run_mutations=args.mutations,
        run_flaky_detection=args.flaky,
    )

    report = analyze_project(str(project_root), config)

    summary = report.summary

    if args.json:
        print(json.dumps(report.to_dict(), indent=2, default=str))
    else:
        print(f"Project healthy: {summary.get('project_healthy', 'unknown')}")
        print(f"Total issues: {summary.get('total_issues', 0)}")
        print(f"Critical: {summary.get('critical_issues', 0)}")
        print(f"Warnings: {summary.get('warnings', 0)}")

        if summary.get("categories"):
            print("\nCategories:")
            for cat, count in sorted(summary["categories"].items()):
                print(f"  {cat}: {count}")

        if report.coverage_gaps:
            print(f"\nTop coverage gaps ({len(report.coverage_gaps)} total):")
            for gap in report.coverage_gaps[:10]:
                print(f"  {gap.get('file', '?')}:{gap.get('line', '?')} - {gap.get('reason', '')}")

    return 0 if summary.get("project_healthy", False) else 1


def main() -> int:
    parser = argparse.ArgumentParser(
        prog="nokrashi",
        description="Code quality checks and test analysis toolkit",
    )
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # run command
    run_parser = subparsers.add_parser("run", help="Run standards tests")
    run_parser.add_argument(
        "--project-root", required=True, help="Path to project root"
    )
    run_parser.add_argument(
        "--dashboard-uid", default="", help="Grafana dashboard UID (optional)"
    )
    run_parser.add_argument(
        "--grafana-url",
        default="",
        help="Grafana base URL (optional, or from GRAFANA_URL env var)",
    )
    run_parser.add_argument(
        "--metrics-interval",
        type=int,
        default=15,
        help="Metrics push interval in seconds (default: 15)",
    )
    run_parser.add_argument(
        "--grafana-token",
        default=None,
        help="Grafana API token (default: from GRAFANA_API_TOKEN env var)",
    )
    run_parser.add_argument(
        "-v", "--verbose", action="store_true", help="Verbose output"
    )

    # analyze command
    analyze_parser = subparsers.add_parser("analyze", help="Run project analysis")
    analyze_parser.add_argument(
        "--project-root", required=True, help="Path to project root"
    )
    analyze_parser.add_argument(
        "--mutations", action="store_true", help="Enable mutation testing (slow)"
    )
    analyze_parser.add_argument(
        "--flaky", action="store_true", help="Enable flaky test detection (slow)"
    )
    analyze_parser.add_argument(
        "--json", action="store_true", help="Output as JSON"
    )

    args = parser.parse_args()

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

    import os

    if args.command == "run":
        if not args.grafana_url:
            args.grafana_url = os.environ.get("GRAFANA_URL", "")
        if not args.grafana_token:
            args.grafana_token = os.environ.get("GRAFANA_API_TOKEN")

        return cmd_run(args)
    elif args.command == "analyze":
        return cmd_analyze(args)

    return 1


if __name__ == "__main__":
    sys.exit(main())
