# #region Test.Api.TranslateCorrectionRoutes [C:3] [TYPE Module] [SEMANTICS test,translate,corrections,api]
# @BRIEF Tests for _correction_routes.py — term correction submission.
# @RELATION BINDS_TO -> [TranslateCorrectionRoutesModule]
# @TEST_EDGE: correction_missing_dict_id -> 422
# @TEST_EDGE: correction_value_error -> 400
# @TEST_EDGE: bulk_correction_value_error -> 400
# @TEST_EDGE: bulk_correction_conflict -> 409

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._correction_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)


# ── submit_correction ──

class TestSubmitCorrection:
    """POST /api/translate/corrections"""

    def test_submit_success(self):
        with patch("src.api.routes.translate._correction_routes.DictionaryManager") as MockDict:
            MockDict.submit_correction.return_value = {"status": "applied", "entry_id": "entry-1"}
            client = _make_client()
            resp = client.post("/api/translate/corrections", json={
                "dictionary_id": "dict-1",
                "source_term": "old term",
                "incorrect_target_term": "wrong",
                "corrected_target_term": "correct",
                "origin_run_id": "run-1",
                "origin_row_key": "row-1",
            })
        assert resp.status_code == 200
        assert resp.json()["status"] == "applied"

    def test_submit_missing_dict_id_422(self):
        client = _make_client()
        resp = client.post("/api/translate/corrections", json={
            "source_term": "term",
            "incorrect_target_term": "wrong",
            "corrected_target_term": "correct",
        })
        assert resp.status_code == 422
        assert "dictionary_id" in resp.text

    def test_submit_value_error_400(self):
        with patch("src.api.routes.translate._correction_routes.DictionaryManager") as MockDict:
            MockDict.submit_correction.side_effect = ValueError("Invalid dictionary")
            client = _make_client()
            resp = client.post("/api/translate/corrections", json={
                "dictionary_id": "dict-bad",
                "source_term": "term",
                "incorrect_target_term": "wrong",
                "corrected_target_term": "correct",
                "origin_run_id": "run-1",
            })
        assert resp.status_code == 400


# ── submit_bulk_corrections ──

class TestSubmitBulkCorrections:
    """POST /api/translate/corrections/bulk"""

    def test_bulk_success(self):
        with patch("src.api.routes.translate._correction_routes.DictionaryManager") as MockDict:
            MockDict.submit_bulk_corrections.return_value = {"status": "applied", "count": 2}
            client = _make_client()
            resp = client.post("/api/translate/corrections/bulk", json={
                "dictionary_id": "dict-1",
                "corrections": [
                    {
                        "source_term": "term1",
                        "incorrect_target_term": "wrong1",
                        "corrected_target_term": "correct1",
                        "origin_run_id": "run-1",
                        "origin_row_key": "row-1",
                    },
                    {
                        "source_term": "term2",
                        "incorrect_target_term": "wrong2",
                        "corrected_target_term": "correct2",
                        "origin_run_id": "run-1",
                        "origin_row_key": "row-2",
                    },
                ],
            })
        assert resp.status_code == 200
        assert resp.json()["count"] == 2

    def test_bulk_conflict_409(self):
        with patch("src.api.routes.translate._correction_routes.DictionaryManager") as MockDict:
            MockDict.submit_bulk_corrections.return_value = {
                "status": "conflicts",
                "conflicts": [{"source_term": "term1", "message": "Existing entry"}],
            }
            client = _make_client()
            resp = client.post("/api/translate/corrections/bulk", json={
                "dictionary_id": "dict-1",
                "corrections": [
                    {
                        "source_term": "term1",
                        "incorrect_target_term": "wrong1",
                        "corrected_target_term": "correct1",
                        "origin_run_id": "run-1",
                        "origin_row_key": "row-1",
                    },
                ],
            })
        assert resp.status_code == 409
        assert "conflicts" in resp.text

    def test_bulk_value_error_400(self):
        with patch("src.api.routes.translate._correction_routes.DictionaryManager") as MockDict:
            MockDict.submit_bulk_corrections.side_effect = ValueError("Invalid data")
            client = _make_client()
            resp = client.post("/api/translate/corrections/bulk", json={
                "dictionary_id": "dict-1",
                "corrections": [],
            })
        assert resp.status_code == 400
# #endregion Test.Api.TranslateCorrectionRoutes
