"""Doctor suite — run diagnostics and parse results."""

from __future__ import annotations

from typing import TYPE_CHECKING

from tests.remote.suites.base import BaseSuite, StepStatus, SuiteResult

if TYPE_CHECKING:
    from tests.remote.runner import RemoteTestRunner


class DoctorSuite(BaseSuite):
    name = "doctor"
    description = "Run llmhosts doctor and verify diagnostics pass"

    async def execute(self, runner: RemoteTestRunner, result: SuiteResult) -> None:
        r = await runner.run_command("llmhosts doctor", timeout=120.0)

        if r.timed_out:
            self._add_step(
                result,
                "run_doctor",
                "Run llmhosts doctor",
                status=StepStatus.ERROR,
                stdout=r.stdout,
                stderr=r.stderr,
                duration_s=r.duration_s,
                error_message="Doctor command timed out",
            )
            return

        # Parse output for pass/warn/fail indicators
        output = r.stdout.lower()
        pass_count = output.count("pass") + output.count("[ok]") + output.count("[green]")
        warn_count = output.count("warn") + output.count("[yellow]")
        fail_count = output.count("fail") + output.count("[red]") + output.count("error")

        self._add_step(
            result,
            "run_doctor",
            f"Run llmhosts doctor (pass={pass_count}, warn={warn_count}, fail={fail_count})",
            status=StepStatus.PASSED if r.success else StepStatus.FAILED,
            stdout=r.stdout,
            stderr=r.stderr,
            duration_s=r.duration_s,
            error_message="" if r.success else f"Doctor exited with code {r.exit_code}",
        )

        # Step 2: Verify no crash (check for Python tracebacks)
        has_traceback = "traceback" in output or "exception" in output
        self._add_step(
            result,
            "no_crash",
            "Verify no Python tracebacks in output",
            status=StepStatus.FAILED if has_traceback else StepStatus.PASSED,
            duration_s=0.0,
            error_message="Python traceback detected in doctor output" if has_traceback else "",
        )
