from __future__ import annotations

import shutil
import tempfile
from importlib.resources import as_file, files
from pathlib import Path

from ocr_pipeline.config import settings
from ocr_pipeline.pipeline import OCRPipeline, PipelineResult
from ocr_pipeline.utils.logging import get_logger

logger = get_logger(__name__)

DEMO_IMAGE_NAME = "demo_screenshot.png"


def demo_image_path() -> Path:
    """Copy the bundled sample screenshot into a fresh temp directory."""
    resource = files("ocr_pipeline.assets") / DEMO_IMAGE_NAME
    target_dir = Path(tempfile.mkdtemp(prefix="ocr-pipeline-demo-"))
    target = target_dir / DEMO_IMAGE_NAME
    with as_file(resource) as source:
        shutil.copy(source, target)
    return target


def _apply_demo_settings(work_dir: Path) -> None:
    """Hermetic demo: guaranteed-safe engine and features, isolated output and DB."""
    settings.ocr.engine = "tesseract"
    settings.entities.enabled = False
    settings.detectors.figures.enabled = False
    settings.detectors.tables.enabled = False
    settings.detectors.captions.enabled = False
    settings.processing.skip_existing = False
    settings.output.base_directory = str(work_dir / "output")
    settings.output.write_consolidated = False
    settings.watch.db_path = str(work_dir / "demo_processed.db")


def run_demo() -> PipelineResult:
    """Run the full pipeline on the bundled sample screenshot."""
    image = demo_image_path()
    _apply_demo_settings(image.parent)
    logger.info("demo_started", image=str(image))
    return OCRPipeline().process_all([image])
