from __future__ import annotations

import argparse
import sys
from pathlib import Path

_agent_root = Path(__file__).resolve().parents[2]
if str(_agent_root) not in sys.path:
    sys.path.insert(0, str(_agent_root))
_src = _agent_root / "src"
if _src.exists() and str(_src) not in sys.path:
    sys.path.insert(0, str(_src))

from tests.pipeline_setup_v4.core.runner import V4Runner
from tests.pipeline_setup_v4.shared.env_loader import load_pipeline_setup_env


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Run isolated component cases for pipeline_setup_v4")
    parser.add_argument("--cases-dir", required=True, help="Directory or file with YAML case files")
    parser.add_argument("--run-name", default="manual_run", help="Run directory name inside cases/*/test_runs")
    ns = parser.parse_args(argv)

    cases_dir = Path(str(ns.cases_dir)).expanduser().resolve()
    load_pipeline_setup_env(start_dir=Path(__file__).resolve().parent)
    runner = V4Runner(cases_dir=cases_dir, run_name=str(ns.run_name).strip() or "manual_run")
    print(f"Cases dir: {cases_dir}")
    results, summary_paths = runner.run()
    passed = sum(1 for item in results if item.passed)
    print(f"Passed: {passed}/{len(results)}")
    for path in summary_paths:
        print(f"Summary: {path}")
    for item in results:
        if not item.passed:
            print(f"FAIL {item.case.case_id}: {'; '.join(item.mismatches)}")
    return 0 if passed == len(results) else 1


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