"""High-level helpers for generating artifact screenshots and comparing against baselines."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Dict

from .before_after import BeforeAfterComparator, BeforeAfterReport
from .screenshot_capture import (
    capture_template_screenshot,
    validate_libreoffice_availability,
)


def _render_preview(template_path: Path, output_path: Path) -> Path:
    """Render a real PNG preview using LibreOffice."""
    if not validate_libreoffice_availability():
        raise RuntimeError("LibreOffice is not available for preview rendering")

    output_path.parent.mkdir(parents=True, exist_ok=True)
    if not capture_template_screenshot(str(template_path), str(output_path)):
        raise RuntimeError(f"Failed to capture screenshot for {template_path}")

    return output_path


@dataclass
class BaselineComparisonResult:
    reports: Dict[str, BeforeAfterReport]
    preview_dir: Path


def run_baseline_comparison(
    output_dir: Path,
    workspace: Path,
    *,
    templates: Dict[str, str] | None = None,
    artifacts_dir: Path | None = None,
    preview_subdir: str = "previews",
    strict: bool = True,
) -> BaselineComparisonResult:
    """Render previews for generated templates and compare against stored baselines.

    Args:
        output_dir: Root folder containing generated/templates
        workspace: Baseline workspace (e.g., tests/baselines)
        templates: Mapping of format -> archive stem (defaults to standard names)
        artifacts_dir: Where to write diff images
        preview_subdir: Folder inside output_dir to store generated previews
    """

    templates = templates or {
        "presentation": "presentation.potx",
    }
    preview_dir = output_dir / preview_subdir
    preview_dir.mkdir(parents=True, exist_ok=True)

    previews: Dict[str, Path] = {}
    for format_type, filename in templates.items():
        archive_path = output_dir / "templates" / filename
        if not archive_path.exists():
            message = f"Template archive missing: {archive_path}"
            if strict:
                raise FileNotFoundError(message)
            continue
        preview_path = preview_dir / f"{format_type}.png"
        _render_preview(archive_path, preview_path)
        previews[format_type] = preview_path

    if strict and not previews:
        raise RuntimeError("No previews generated for baseline comparison")

    comparator = BeforeAfterComparator(
        artifacts_dir=artifacts_dir or (output_dir / "reports" / "visual-diffs")
    )

    reports: Dict[str, BeforeAfterReport] = {}
    for format_type, preview in previews.items():
        report = comparator.compare_stored_baseline(
            tier="community",
            category=format_type,
            template_name=format_type,
            candidate_image=preview,
            workspace=workspace,
        )
        reports[format_type] = report

    return BaselineComparisonResult(reports=reports, preview_dir=preview_dir)
