# #region Test.Api.TranslateRunHistoryRoutes [C:3] [TYPE Module] [SEMANTICS test,translate,history,runs,batches,api]
# @BRIEF Tests for _run_history_routes.py — run history, status, records, batches.
# @RELATION BINDS_TO -> [TranslateRunHistoryRoutesModule]
# @TEST_EDGE: run_history_value_error -> 404
# @TEST_EDGE: run_status_value_error -> 404
# @TEST_EDGE: run_records_value_error -> 404
# @TEST_EDGE: batches_exception -> 400

import os
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")

import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

_src = str(Path(__file__).resolve().parent.parent.parent / "src")
if _src not in sys.path:
    sys.path.insert(0, _src)


def _make_client(overrides: dict | None = None) -> TestClient:
    from src.api.routes.translate._run_history_routes import router
    from src.dependencies import get_current_user, get_config_manager, get_db, has_permission, require_feature
    from src.schemas.auth import User, RoleSchema

    app = FastAPI()
    app.include_router(router)

    mock_user = User(
        id="user-1", username="admin", email="admin@x.com",
        auth_source="LOCAL",
        created_at=__import__("datetime").datetime.now(),
        roles=[RoleSchema(id="r1", name="Admin", description="", permissions=[])],
    )

    defaults = {
        get_current_user: lambda: mock_user,
        get_config_manager: lambda: MagicMock(),
        get_db: lambda: MagicMock(),
        has_permission: lambda *a, **kw: lambda: None,
        require_feature: lambda *a, **kw: lambda: None,
    }
    if overrides:
        defaults.update(overrides)
    for dep, mock_fn in defaults.items():
        app.dependency_overrides[dep] = mock_fn
    return TestClient(app)


# ── get_run_history ──

class TestGetRunHistory:
    """GET /api/translate/jobs/{job_id}/runs"""

    def test_run_history_success(self):
        mock_orch = MagicMock()
        mock_orch.get_run_history.return_value = (1, [{"id": "run-1", "status": "completed"}])

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/jobs/job-1/runs")
        assert resp.status_code == 200
        data = resp.json()
        assert data["total"] == 1
        assert len(data["items"]) == 1
        assert data["page"] == 1

    def test_run_history_not_found_404(self):
        mock_orch = MagicMock()
        mock_orch.get_run_history.side_effect = ValueError("Job not found")

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/jobs/job-missing/runs")
        assert resp.status_code == 404


# ── get_run_status ──

class TestGetRunStatus:
    """GET /api/translate/runs/{run_id}"""

    def test_run_status_success(self):
        mock_orch = MagicMock()
        mock_orch.get_run_status.return_value = {"id": "run-1", "status": "running"}

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/runs/run-1")
        assert resp.status_code == 200
        assert resp.json()["status"] == "running"

    def test_run_status_not_found_404(self):
        mock_orch = MagicMock()
        mock_orch.get_run_status.side_effect = ValueError("Run not found")

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/runs/run-missing")
        assert resp.status_code == 404


# ── get_run_records ──

class TestGetRunRecords:
    """GET /api/translate/runs/{run_id}/records"""

    def test_run_records_success(self):
        mock_orch = MagicMock()
        mock_orch.get_run_records.return_value = {
            "items": [{"id": "rec-1"}],
            "total": 1,
            "page": 1,
            "page_size": 50,
        }

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/runs/run-1/records")
        assert resp.status_code == 200
        assert resp.json()["total"] == 1

    def test_run_records_with_filters(self):
        mock_orch = MagicMock()
        mock_orch.get_run_records.return_value = {
            "items": [],
            "total": 0,
            "page": 1,
            "page_size": 50,
        }

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/runs/run-1/records?status=failed&deduplicate=true")
        assert resp.status_code == 200
        mock_orch.get_run_records.assert_called_once_with(
            "run-1", page=1, page_size=50, status_filter="failed", deduplicate=True
        )

    def test_run_records_not_found_404(self):
        mock_orch = MagicMock()
        mock_orch.get_run_records.side_effect = ValueError("Run not found")

        with patch("src.api.routes.translate._run_history_routes.TranslationOrchestrator",
                   return_value=mock_orch):
            client = _make_client()
            resp = client.get("/api/translate/runs/run-missing/records")
        assert resp.status_code == 404


# ── get_batches ──

class TestGetBatches:
    """GET /api/translate/runs/{run_id}/batches"""

    def test_batches_success(self):
        from datetime import datetime, UTC
        mock_db = MagicMock()
        mock_batch = MagicMock()
        mock_batch.id = "batch-1"
        mock_batch.run_id = "run-1"
        mock_batch.batch_index = 0
        mock_batch.status = "completed"
        mock_batch.total_records = 10
        mock_batch.successful_records = 9
        mock_batch.failed_records = 1
        mock_batch.started_at = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)
        mock_batch.completed_at = datetime(2026, 1, 1, 12, 5, 0, tzinfo=UTC)
        mock_batch.created_at = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)

        mock_db.query.return_value.filter.return_value.order_by.return_value.all.return_value = [mock_batch]

        from src.dependencies import get_db
        client = _make_client({get_db: lambda: mock_db})
        resp = client.get("/api/translate/runs/run-1/batches")
        assert resp.status_code == 200
        data = resp.json()
        assert len(data) == 1
        assert data[0]["id"] == "batch-1"
        assert data[0]["status"] == "completed"
        assert data[0]["batch_index"] == 0

    def test_batches_empty(self):
        mock_db = MagicMock()
        mock_db.query.return_value.filter.return_value.order_by.return_value.all.return_value = []

        from src.dependencies import get_db
        client = _make_client({get_db: lambda: mock_db})
        resp = client.get("/api/translate/runs/run-1/batches")
        assert resp.status_code == 200
        assert resp.json() == []

    def test_batches_db_error_400(self):
        mock_db = MagicMock()
        mock_db.query.return_value.filter.return_value.order_by.return_value.all.side_effect = Exception("DB error")

        from src.dependencies import get_db
        client = _make_client({get_db: lambda: mock_db})
        resp = client.get("/api/translate/runs/run-1/batches")
        assert resp.status_code == 400
# #endregion Test.Api.TranslateRunHistoryRoutes
