# #region TestTranslateCorrectionsIntegration [C:3] [TYPE Module] [SEMANTICS test,translate,corrections,integration]
# @BRIEF Integration tests for InlineCorrectionService and BulkFindReplaceService with real PostgreSQL.
# @RELATION BINDS_TO -> [InlineCorrectionService]
# @RELATION BINDS_TO -> [BulkFindReplaceService]
#
# @TEST_CONTRACT InlineCorrectionService ->
#   apply_inline_edit: db + record + language + text -> language_updated
#
# @TEST_CONTRACT BulkFindReplaceService ->
#   apply: db + run_id + pattern + replacement -> rows_affected in result dict
#   preview: db + run_id + pattern -> list of matching items
#
# @TEST_EDGE: non_existent_record -> ValueError on inline edit
# @TEST_EDGE: non_existent_language -> ValueError
# @TEST_EDGE: empty_replace_run -> rows_affected=0, no error
import pytest
import uuid

from sqlalchemy.orm import Session

from src.models.translate import (
    TranslationJob,
    TranslationRun,
    TranslationBatch,
    TranslationRecord,
    TranslationLanguage,
)
from src.plugins.translate.service_inline_correction import InlineCorrectionService


# #region TestInlineCorrectionIntegration [C:3] [TYPE Class]
class TestInlineCorrectionIntegration:
    """Verify InlineCorrectionService operations with real PostgreSQL."""

    def _create_full_run_tree(self, db: Session, lang_status: str = "pending") -> tuple:
        job = TranslationJob(
            name="Inline Test Job", status="ACTIVE",
            source_dialect="postgresql", target_dialect="clickhouse",
            translation_column="name", target_column="name",
            target_languages=["ru", "de"],
            created_by="test_user",
        )
        db.add(job)
        db.commit()
        db.refresh(job)

        run = TranslationRun(
            job_id=job.id, status="COMPLETED", trigger_type="manual",
        )
        db.add(run)
        db.commit()
        db.refresh(run)

        batch = TranslationBatch(
            run_id=run.id, batch_index=0, status="COMPLETED",
            total_records=1, successful_records=1,
        )
        db.add(batch)
        db.commit()
        db.refresh(batch)

        record = TranslationRecord(
            batch_id=batch.id, run_id=run.id,
            source_sql="Hello World",
            target_sql="Hola Mundo",
            status="SUCCESS",
            source_hash=uuid.uuid4().hex,
        )
        db.add(record)
        db.commit()
        db.refresh(record)

        lang = TranslationLanguage(
            record_id=record.id,
            language_code="ru",
            source_language_detected="en",
            translated_value="Привет мир",
            final_value="Привет мир",
            status=lang_status,
        )
        db.add(lang)
        db.commit()
        db.refresh(lang)

        return job, run, batch, record, lang

    # #region test_apply_inline_edit [C:2] [TYPE Function]
    def test_apply_inline_edit(self, db_session: Session):
        _, _, _, record, lang = self._create_full_run_tree(db_session)

        result = InlineCorrectionService.apply_inline_edit(
            db=db_session, run_id=record.run_id,
            record_id=record.id, language_code="ru",
            final_value="Здравствуй мир",
        )

        assert result["language_code"] == "ru"
        assert result["final_value"] == "Здравствуй мир"

        db_session.refresh(lang)
        assert lang.final_value == "Здравствуй мир"
        assert lang.user_edit == "Здравствуй мир"
    # #endregion test_apply_inline_edit

    # #region test_apply_inline_edit_non_existent_record [C:2] [TYPE Function]
    def test_apply_inline_edit_non_existent_record(self, db_session: Session):
        with pytest.raises((ValueError, KeyError)):
            InlineCorrectionService.apply_inline_edit(
                db=db_session, run_id=str(uuid.uuid4()),
                record_id=str(uuid.uuid4()), language_code="ru",
                final_value="test",
            )
    # #endregion test_apply_inline_edit_non_existent_record

    # #region test_apply_inline_edit_non_existent_language [C:2] [TYPE Function]
    def test_apply_inline_edit_non_existent_language(self, db_session: Session):
        _, _, _, record, _ = self._create_full_run_tree(db_session)

        with pytest.raises(ValueError, match="not found"):
            InlineCorrectionService.apply_inline_edit(
                db=db_session, run_id=record.run_id,
                record_id=record.id, language_code="nonexistent",
                final_value="test",
            )
    # #endregion test_apply_inline_edit_non_existent_language
# #endregion TestInlineCorrectionIntegration
# #endregion TestTranslateCorrectionsIntegration
