#!/usr/bin/env python3
"""Run kanban recovery smoke tests against storage+dispatcher (no HTTP).

Usage:
    pyenv shell ai_env_312
    python scripts/kanban_recovery_smoke.py

Optional live backend check (requires mugi_backend on port):
    python scripts/kanban_recovery_smoke.py --http http://127.0.0.1:8321
"""
from __future__ import annotations

import argparse
import os
import subprocess
import sys
import unittest


def _run_unit_tests() -> int:
    repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    cmd = [
        sys.executable,
        "-m",
        "pytest",
        "tests/test_kanban_recovery_regression.py",
        "tests/test_kanban_dispatcher.py::TestKanbanDispatcherClaimComplete::test_salvage_blocked_handoff_marks_blocked_not_done",
        "tests/test_tool_call_loop_detector.py::TestKanbanObserveLoopHardStop",
        "tests/test_agent_loop_toolcall_fallback.py::test_query_recovery_reuses_prior_tool_call_query",
        "tests/test_agent_loop_toolcall_fallback.py::test_query_recovery_prefers_assistant_quote_over_sticky_task_title",
        "-q",
        "--tb=short",
    ]
    print("Running:", " ".join(cmd))
    return subprocess.call(cmd, cwd=repo)


def _http_health(base: str) -> bool:
    try:
        import urllib.request

        with urllib.request.urlopen(f"{base.rstrip('/')}/health", timeout=3) as resp:
            return resp.status == 200
    except Exception as exc:
        print(f"HTTP health failed: {exc}")
        return False


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--http", default="", help="Optional backend base URL for /health")
    args = parser.parse_args()

    os.environ.setdefault("MUGI_SKIP_BACKEND_BOOTSTRAP", "1")
    rc = _run_unit_tests()
    if rc != 0:
        return rc

    if args.http:
        if _http_health(args.http):
            print(f"Backend OK: {args.http}")
        else:
            print(f"Backend not reachable at {args.http}", file=sys.stderr)
            return 2

    print("kanban recovery smoke: PASS")
    return 0


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