# #region TestReportsDetailApi [TYPE Module] [C:3] [SEMANTICS tests, reports, api, detail, diagnostics]
# @RELATION BINDS_TO -> SrcRoot
# @BRIEF Contract tests for GET /api/reports/{report_id} detail endpoint behavior.
# @LAYER Domain
# @INVARIANT  Detail endpoint tests must keep deterministic assertions for success and not-found contracts.
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace

from fastapi.testclient import TestClient

from src.app import app
from src.core.task_manager.models import Task, TaskStatus
from src.dependencies import get_current_user, get_task_manager


# @DEBT: Divergent _FakeTaskManager definition. Canonical version should be in conftest.py. Authz variant is missing get_all_tasks().
# #region _FakeTaskManager [TYPE Class] [C:1]
# @RELATION BINDS_TO -> [TestReportsDetailApi]
# @BRIEF Minimal task-manager double exposing pre-seeded tasks to detail endpoint under test.
# @INVARIANT  get_all_tasks returns exactly seeded tasks list.
class _FakeTaskManager:
    def __init__(self, tasks):
        self._tasks = tasks
    def get_all_tasks(self):
        return self._tasks
# #endregion _FakeTaskManager
# #region _admin_user [TYPE Function]
# @RELATION BINDS_TO -> TestReportsDetailApi
# @BRIEF Provide admin principal fixture accepted by reports detail authorization policy.
def _admin_user():
    role = SimpleNamespace(name="Admin", permissions=[])
    return SimpleNamespace(username="test-admin", roles=[role])
# #endregion _admin_user
# #region _make_task [TYPE Function]
# @RELATION BINDS_TO -> TestReportsDetailApi
# @BRIEF Build deterministic Task payload for reports detail endpoint contract assertions.
def _make_task(task_id: str, plugin_id: str, status: TaskStatus, result=None):
    now = datetime.now(UTC)
    return Task(
        id=task_id,
        plugin_id=plugin_id,
        status=status,
        started_at=now - timedelta(minutes=2),
        finished_at=now - timedelta(minutes=1)
        if status != TaskStatus.RUNNING
        else None,
        params={"environment_id": "env-1"},
        result=result or {"summary": f"{plugin_id} result"},
    )
# #endregion _make_task
# #region test_get_report_detail_success [TYPE Function]
# @RELATION BINDS_TO -> TestReportsDetailApi
# @BRIEF Validate report detail endpoint returns report body with diagnostics and next actions for existing task.
def test_get_report_detail_success():
    task = _make_task(
        "detail-1",
        "superset-migration",
        TaskStatus.FAILED,
        result={
            "error": {
                "message": "Step failed",
                "next_actions": ["Check mapping", "Retry"],
            }
        },
    )
    app.dependency_overrides[get_current_user] = lambda: _admin_user()
    app.dependency_overrides[get_task_manager] = lambda: _FakeTaskManager([task])
    try:
        client = TestClient(app)
        response = client.get("/api/reports/detail-1")
        assert response.status_code == 200
        data = response.json()
        assert "report" in data
        assert data["report"]["report_id"] == "detail-1"
        assert "diagnostics" in data
        assert "next_actions" in data
    finally:
        app.dependency_overrides.clear()
# #endregion test_get_report_detail_success
# #region test_get_report_detail_not_found [TYPE Function]
# @RELATION BINDS_TO -> TestReportsDetailApi
# @BRIEF Validate report detail endpoint returns 404 when requested report identifier is absent.
def test_get_report_detail_not_found():
    task = _make_task("detail-2", "superset-backup", TaskStatus.SUCCESS)
    app.dependency_overrides[get_current_user] = lambda: _admin_user()
    app.dependency_overrides[get_task_manager] = lambda: _FakeTaskManager([task])
    try:
        client = TestClient(app)
        response = client.get("/api/reports/unknown-id")
        assert response.status_code == 404
    finally:
        app.dependency_overrides.clear()
# #endregion test_get_report_detail_not_found
# #endregion TestReportsDetailApi
