"""Tests for audit checking task type validity and LLM reachability."""

from unittest.mock import MagicMock
from milco.core.run_context import RunContext
from milco.audit.auditor import run_audit

import milco.tasks.map_gen  # noqa: F401 -- force registration


def _make_ctx(tmp_path, task_type=None, llm=None):
    contract_text = (
        "# Task Contract\n\n"
        "## Goal\n\nTest.\n\n"
        "## Scope\n\nTest.\n\n"
        "## Out of scope\n\nNone.\n\n"
        "## Success Criteria\n\nPass.\n\n"
        "## Constraints\n\nNone.\n\n"
        "## Approvals required\n\nCONFIRM APPLY\n\n"
        "## Notes\n\nNone.\n"
    )
    contract = tmp_path / "TASK_CONTRACT.md"
    contract.write_text(contract_text, encoding="utf-8")
    return RunContext(
        repo_root=tmp_path,
        run_id="test-audit",
        apply_mode=False,
        contract_path=str(contract),
        task_type=task_type,
        llm=llm,
    )


def test_audit_unknown_task_type_error(tmp_path):
    ctx = _make_ctx(tmp_path, task_type="nonexistent")
    result = run_audit(ctx)
    assert any("task type" in e.lower() for e in result["errors"])


def test_audit_known_task_type_no_error(tmp_path):
    ctx = _make_ctx(tmp_path, task_type="map-gen")
    result = run_audit(ctx)
    assert not any("task type" in e.lower() for e in result["errors"])


def test_audit_llm_ping_failure(tmp_path):
    mock_llm = MagicMock()
    mock_llm.ping.return_value = False
    mock_llm.name = "ollama"
    ctx = _make_ctx(tmp_path, task_type="map-gen", llm=mock_llm)
    result = run_audit(ctx)
    assert any("reachable" in e.lower() for e in result["errors"])


def test_audit_llm_ping_success(tmp_path):
    mock_llm = MagicMock()
    mock_llm.ping.return_value = True
    mock_llm.name = "ollama"
    ctx = _make_ctx(tmp_path, task_type="map-gen", llm=mock_llm)
    result = run_audit(ctx)
    assert not any("reachable" in e.lower() for e in result["errors"])
