# #region TranslateTestConftest [C:2] [TYPE Module] [SEMANTICS test, conftest, translate]
# @BRIEF Shared fixtures for translate plugin tests.
import uuid
from datetime import UTC, datetime

from sqlalchemy import create_engine, event
from sqlalchemy.orm import Session, sessionmaker
import pytest

from src.models.translate import Base, TranslationBatch, TranslationJob, TranslationRun
from src.plugins.translate.events import TranslationEventLog

# Shared IDs for FK references
JOB_ID = "test-job-id"
RUN_ID = "test-run-id"


@pytest.fixture(scope="function")
def db_session():
    """Create a fresh in-memory SQLite DB with FK enforcement and base records."""
    engine = create_engine("sqlite:///:memory:")
    @event.listens_for(engine, "connect")
    def _set_sqlite_pragma(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()
    Base.metadata.create_all(bind=engine)
    session = sessionmaker(bind=engine)()
    # Create base TranslationJob
    job = TranslationJob(id=JOB_ID, name="Base Test Job", status="ACTIVE",
                         source_dialect="en", target_dialect="fr")
    session.add(job)
    session.commit()
    yield session
    session.close()
    Base.metadata.drop_all(bind=engine)


BATCH_ID = "batch-1"

@pytest.fixture(scope="function")
def db_with_run(db_session):
    """Create a TranslationRun and TranslationBatch in addition to the base job."""
    run = TranslationRun(id=RUN_ID, job_id=JOB_ID, status="RUNNING",
                         started_at=datetime.now(UTC))
    db_session.add(run)
    db_session.flush()  # Must flush run before batch to satisfy FK ordering with SQLite
    batch = TranslationBatch(id=BATCH_ID, run_id=RUN_ID, batch_index=0, status="PENDING")
    db_session.add(batch)
    db_session.commit()
    # Log RUN_STARTED event so downstream events can be logged
    event_log = TranslationEventLog(db_session)
    event_log.log_event(job_id=JOB_ID, run_id=RUN_ID, event_type="RUN_STARTED",
                        payload={}, created_by="test")
    return db_session, RUN_ID
# #endregion TranslateTestConftest
