"""albus validate -- Run validation suites against live agents."""

from __future__ import annotations

import asyncio
from pathlib import Path

from core.validation.runner import ValidationRunner
from core.validation.snapshot import write_snapshot
from server.transport.cli._models import ValidateArgs


def cmd_validate(args: ValidateArgs) -> int:
    """Run a validation suite against live agents."""
    if not args.target:
        print("Error: validation suite YAML file required")
        return 2

    target_path = Path(args.target)
    if not target_path.exists():
        print(f"Error: File not found: {args.target}")
        return 1

    async def _validate() -> int:
        runner = ValidationRunner(verbose=args.verbose, stop_on_fail=args.stop_on_fail)
        result = await runner.run_suite(target_path)

        print()
        if result.setup_error:
            print(f"SETUP FAILED: {result.setup_error}")
            return 1

        passed_str = "PASSED" if result.passed else "FAILED"
        print(f"{'=' * 60}")
        print(f"  {result.suite_name or result.suite_id}: {passed_str}")
        print(f"  Cases: {result.cases_passed}/{result.cases_run} passed")
        print(f"  Duration: {result.total_duration_ms}ms")
        print(f"{'=' * 60}")

        if result.cases_failed > 0:
            print("\nFailed cases:")
            for cr in result.results:
                if not cr.passed:
                    print(f"  [{cr.case_id}]")
                    for f in cr.failures:
                        print(f"    {f.check}: expected {f.expected}")
                        print(f"      actual: {f.actual}")
                    if cr.error:
                        print(f"    error: {cr.error}")

        if result.passed:
            snapshot_path = write_snapshot(result, target_path)
            print(f"\nSnapshot: {snapshot_path}")

        return 0 if result.passed else 1

    return asyncio.run(_validate())
