# #region TranslationStageRunner [C:4] [TYPE Class] [SEMANTICS sqlalchemy, translate, execution, superset]
# @BRIEF Coordinate translation run execution, retry, and cancellation via delegated components.
# @PRE Database session and config manager are available. Run is in valid state.
# @POST Run is executed; events recorded.
# @SIDE_EFFECT LLM calls, DB writes, Superset API calls.
# @RELATION DEPENDS_ON -> [TranslationExecutionEngine]
# @RELATION DEPENDS_ON -> [TranslationRunRetryManager]
# @RELATION DEPENDS_ON -> [TranslationEventLog]

from collections.abc import Callable

from sqlalchemy.orm import Session

from ...core.config_manager import ConfigManager
from ...core.logger import belief_scope
from ...models.translate import TranslationRun
from .events import TranslationEventLog
from .orchestrator_exec import TranslationExecutionEngine
from .orchestrator_retry import TranslationRunRetryManager


class TranslationStageRunner:
    """Coordinate translation run execution, retry, and cancellation via delegated components."""

    def __init__(
        self,
        db: Session,
        config_manager: ConfigManager,
        event_log: TranslationEventLog,
        current_user: str | None = None,
    ):
        self.db = db
        self.config_manager = config_manager
        self.event_log = event_log
        self.current_user = current_user
        self._executor_engine = TranslationExecutionEngine(db, config_manager, event_log, current_user)
        self._retry_mgr = TranslationRunRetryManager(db, config_manager, event_log, current_user)

    # region execute_run [TYPE Function]
    # @PURPOSE: Execute a translation run: dispatch executor, generate SQL, submit to Superset.
    # @PRE  run is in PENDING status.
    # @POST  Run is executed, SQL generated, Superset submission attempted.
    # @SIDE_EFFECT  LLM calls, DB writes, Superset API calls.
    def execute_run(
        self,
        run: TranslationRun,
        on_batch_progress: Callable[[str, int, int, int, int], None] | None = None,
        skip_insert: bool = False,
    ) -> TranslationRun:
        with belief_scope("TranslationStageRunner.execute_run"):
            return self._executor_engine.execute_run(
                run=run,
                on_batch_progress=on_batch_progress,
                skip_insert=skip_insert,
            )
    # endregion execute_run

    # region retry_failed_batches [TYPE Function]
    # @PURPOSE: Retry failed batches in a run.
    def retry_failed_batches(self, run_id: str) -> TranslationRun:
        return self._retry_mgr.retry_failed_batches(run_id)
    # endregion retry_failed_batches

    # region retry_insert [TYPE Function]
    # @PURPOSE: Retry the SQL insert phase for a completed run.
    def retry_insert(self, run_id: str) -> TranslationRun:
        return self._retry_mgr.retry_insert(run_id)
    # endregion retry_insert

    # region cancel_run [TYPE Function]
    # @PURPOSE: Cancel a running translation.
    def cancel_run(self, run_id: str) -> TranslationRun:
        return self._retry_mgr.cancel_run(run_id)
    # endregion cancel_run

# #endregion TranslationStageRunner
