"""텍스트 Phase StepRunner — text_cleanup."""

import logging
from typing import Any, Dict

from app.core.step_runner import StepRunner

logger = logging.getLogger(__name__)


class TextCleanupStep(StepRunner):
    """Step 1: PDF → Gemini Flash Lite로 텍스트 추출."""

    def _execute(self, mode="resume") -> Dict[str, Any]:
        from app.models.project import Episode
        from sqlalchemy.orm import undefer

        ep = self.db.query(Episode).options(undefer(Episode.fulltext)).filter(
            Episode.id == self.episode_id
        ).first()
        if not ep:
            from app.core.errors import AppError
            raise AppError(code="step.no_episode", message="에피소드를 찾을 수 없습니다.", status_code=400)

        # PDF 경로에서 Gemini로 직접 추출 (파일 존재 확인 포함)
        import os
        pdf_path = ep.source_path
        if pdf_path and os.path.isfile(pdf_path):
            from app.modules.pipeline.text_cleaner import extract_text_from_pdf_llm
            cleaned = extract_text_from_pdf_llm(
                pdf_path=pdf_path,
                project_config=self.project_config,
                opik_metadata=self.build_opik_metadata(),
            )
        else:
            # PDF 경로 없거나 파일 없으면 기존 fulltext fallback
            if pdf_path:
                logger.warning("text_cleanup: source_path '%s' 파일 없음, fulltext fallback", pdf_path)
            else:
                logger.warning("text_cleanup: source_path 없음, fulltext 그대로 사용")
            cleaned = ep.fulltext or ""

        original_length = len(ep.fulltext) if ep.fulltext else 0

        return {
            "completed_count": 1,
            "applicable_count": 1,
            "failed_count": 0,
            "data": {
                "cleaned_text": cleaned,
                "original_length": original_length,
                "cleaned_length": len(cleaned),
            },
        }
