# [DEF:backend.tests.test_reports_openapi_conformance:Module]
# @TIER: STANDARD
# @SEMANTICS: tests, reports, openapi, conformance
# @PURPOSE: Validate implemented reports payload shape against OpenAPI-required top-level contract fields.
# @LAYER: Domain (Tests)
# @RELATION: TESTS -> specs/020-task-reports-design/contracts/reports-api.openapi.yaml
# @INVARIANT: List and detail payloads include required contract keys.

from datetime import datetime
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


class _FakeTaskManager:
    def __init__(self, tasks):
        self._tasks = tasks

    def get_all_tasks(self):
        return self._tasks


def _admin_user():
    role = SimpleNamespace(name="Admin", permissions=[])
    return SimpleNamespace(username="test-admin", roles=[role])


def _task(task_id: str, plugin_id: str, status: TaskStatus):
    now = datetime.utcnow()
    return Task(
        id=task_id,
        plugin_id=plugin_id,
        status=status,
        started_at=now,
        finished_at=now if status != TaskStatus.RUNNING else None,
        params={"environment_id": "env-1"},
        result={"summary": f"{plugin_id} {status.value.lower()}"},
    )


def test_reports_list_openapi_required_keys():
    tasks = [
        _task("r-1", "superset-backup", TaskStatus.SUCCESS),
        _task("r-2", "superset-migration", TaskStatus.FAILED),
    ]
    app.dependency_overrides[get_current_user] = lambda: _admin_user()
    app.dependency_overrides[get_task_manager] = lambda: _FakeTaskManager(tasks)

    try:
        client = TestClient(app)
        response = client.get("/api/reports")
        assert response.status_code == 200

        body = response.json()
        required = {"items", "total", "page", "page_size", "has_next", "applied_filters"}
        assert required.issubset(body.keys())
    finally:
        app.dependency_overrides.clear()


def test_reports_detail_openapi_required_keys():
    tasks = [_task("r-3", "llm_dashboard_validation", TaskStatus.SUCCESS)]
    app.dependency_overrides[get_current_user] = lambda: _admin_user()
    app.dependency_overrides[get_task_manager] = lambda: _FakeTaskManager(tasks)

    try:
        client = TestClient(app)
        response = client.get("/api/reports/r-3")
        assert response.status_code == 200

        body = response.json()
        assert "report" in body
    finally:
        app.dependency_overrides.clear()


# [/DEF:backend.tests.test_reports_openapi_conformance:Module]