# #region Test.Api.TranslateMetricsRoutes [C:3] [TYPE Module] [SEMANTICS test,translate,metrics,api]
# @BRIEF Tests for _metrics_routes.py — translation metrics endpoints.
# @RELATION BINDS_TO -> [TranslateMetricsRoutesModule]
# @TEST_EDGE: metrics_value_error -> 404
# @TEST_EDGE: job_metrics_value_error -> 404

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._metrics_routes import router
    from src.dependencies import get_current_user, 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_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_metrics ──

class TestGetMetrics:
    """GET /api/translate/metrics"""

    def test_get_all_metrics_success(self):
        mock_metrics = MagicMock()
        mock_metrics.get_all_metrics.return_value = {
            "total_translations": 100,
            "success_rate": 0.95,
        }

        with patch("src.api.routes.translate._metrics_routes.TranslationMetrics",
                   return_value=mock_metrics):
            client = _make_client()
            resp = client.get("/api/translate/metrics")
        assert resp.status_code == 200
        assert resp.json()["total_translations"] == 100

    def test_get_job_metrics_with_job_id(self):
        mock_metrics = MagicMock()
        mock_metrics.get_job_metrics.return_value = {
            "job_id": "job-1",
            "total_translations": 50,
            "success_rate": 0.90,
        }

        with patch("src.api.routes.translate._metrics_routes.TranslationMetrics",
                   return_value=mock_metrics):
            client = _make_client()
            resp = client.get("/api/translate/metrics?job_id=job-1")
        assert resp.status_code == 200
        assert resp.json()["job_id"] == "job-1"

    def test_get_metrics_not_found_404(self):
        mock_metrics = MagicMock()
        mock_metrics.get_all_metrics.side_effect = ValueError("No metrics found")

        with patch("src.api.routes.translate._metrics_routes.TranslationMetrics",
                   return_value=mock_metrics):
            client = _make_client()
            resp = client.get("/api/translate/metrics")
        assert resp.status_code == 404


# ── get_job_metrics ──

class TestGetJobMetrics:
    """GET /api/translate/jobs/{job_id}/metrics"""

    def test_job_metrics_success(self):
        mock_metrics = MagicMock()
        mock_metrics.get_job_metrics.return_value = {
            "job_id": "job-1",
            "total_translations": 25,
        }

        with patch("src.api.routes.translate._metrics_routes.TranslationMetrics",
                   return_value=mock_metrics):
            client = _make_client()
            resp = client.get("/api/translate/jobs/job-1/metrics")
        assert resp.status_code == 200
        assert resp.json()["job_id"] == "job-1"

    def test_job_metrics_not_found_404(self):
        mock_metrics = MagicMock()
        mock_metrics.get_job_metrics.side_effect = ValueError("Job not found")

        with patch("src.api.routes.translate._metrics_routes.TranslationMetrics",
                   return_value=mock_metrics):
            client = _make_client()
            resp = client.get("/api/translate/jobs/job-missing/metrics")
        assert resp.status_code == 404
# #endregion Test.Api.TranslateMetricsRoutes
