"""
CLI for contracts_http tool.
"""

import argparse
import sys
import time

from .config import config
from .core import discover_tests, start_test_run, get_run_status


def cmd_discover(args):
    """List discovered tests."""
    tests = discover_tests()

    if args.json:
        import json
        print(json.dumps([
            {
                "id": t.id,
                "module": t.module,
                "class": t.class_name,
                "method": t.method_name,
                "doc": t.doc,
            }
            for t in tests
        ], indent=2))
    else:
        print(f"Discovered {len(tests)} tests:\n")

        # Group by module
        by_module = {}
        for t in tests:
            if t.module not in by_module:
                by_module[t.module] = []
            by_module[t.module].append(t)

        for module, module_tests in sorted(by_module.items()):
            print(f"  {module}:")
            for t in module_tests:
                print(f"    - {t.class_name}.{t.method_name}")
            print()


def cmd_run(args):
    """Run tests."""
    print(f"Target: {config['CONTRACT_TEST_URL']}")
    print()

    # Filter tests if pattern provided
    test_ids = None
    if args.pattern:
        all_tests = discover_tests()
        test_ids = [
            t.id for t in all_tests
            if args.pattern.lower() in t.id.lower()
        ]
        if not test_ids:
            print(f"No tests matching pattern: {args.pattern}")
            return 1
        print(f"Running {len(test_ids)} tests matching '{args.pattern}'")
    else:
        print("Running all tests")

    print()

    # Start run
    run_id = start_test_run(test_ids)

    # Poll until complete
    while True:
        status = get_run_status(run_id)
        if not status:
            print("Error: Run not found")
            return 1

        # Print progress
        if status.current_test:
            sys.stdout.write(f"\r  Running: {status.current_test[:60]}...")
            sys.stdout.flush()

        if status.status in ("completed", "failed"):
            sys.stdout.write("\r" + " " * 80 + "\r")  # Clear line
            break

        time.sleep(0.5)

    # Print results
    print(f"Results: {status.passed} passed, {status.failed} failed, {status.skipped} skipped")
    print()

    # Print failures
    failures = [r for r in status.results if r.status.value in ("failed", "error")]
    if failures:
        print("Failures:")
        for f in failures:
            print(f"\n  {f.test_id}")
            print(f"    {f.error_message}")

    return 1 if failures else 0


def main(args=None):
    parser = argparse.ArgumentParser(
        description="Contract HTTP Tests - Pure HTTP test runner"
    )
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # discover command
    discover_parser = subparsers.add_parser("discover", help="List discovered tests")
    discover_parser.add_argument("--json", action="store_true", help="Output as JSON")

    # run command
    run_parser = subparsers.add_parser("run", help="Run tests")
    run_parser.add_argument("pattern", nargs="?", help="Filter tests by pattern (e.g., 'mascotas', 'pet_owners')")

    args = parser.parse_args(args)

    if args.command == "discover":
        cmd_discover(args)
    elif args.command == "run":
        sys.exit(cmd_run(args))
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
