"""Task-oriented capability index for the public screenshot surface.

Use this module when you need to discover which stable helper fits a screenshot
workflow. The index is intentionally small and points to public entrypoints
instead of implementation details.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Final


@dataclass(frozen=True, slots=True)
class Capability:
    """Describe one task-oriented public capability exposed by screenshot."""

    slug: str
    task: str
    preferred_import: str
    summary: str
    keywords: tuple[str, ...] = ()
    extras: tuple[str, ...] = ()
    example: str = ""

    def searchable_text(self) -> str:
        """Return the lowercase text used for simple free-text matching."""

        return " ".join(
            (
                self.slug,
                self.task,
                self.preferred_import,
                self.summary,
                " ".join(self.keywords),
                " ".join(self.extras),
                self.example,
            )
        ).lower()


CAPABILITIES: Final[tuple[Capability, ...]] = (
    Capability(
        slug="local-cli-jsonl",
        task="Local CLI / JSONL batch capture",
        preferred_import="screenshot local --input jobs.jsonl --output-dir ./out",
        summary=(
            "Use for local screenshot runs, JSONL job specs, summary files, and backend selection."
        ),
        keywords=(
            "cli",
            "jsonl",
            "batch",
            "summary",
            "backend",
            "partial",
            "output-dir",
        ),
        example=(
            "screenshot local --input jobs.jsonl --output-dir ./out --summary-file summary.json"
        ),
    ),
    Capability(
        slug="playwright-capture",
        task="Programmatic Playwright capture",
        preferred_import=(
            "from screenshot import capture_screenshots_async; "
            "from screenshot.models import "
            "CaptureOptions, MotionSnapshotRequest, ScreenshotArtifactsRequest, ScreenshotOptions"
        ),
        summary=(
            "Use for Playwright-backed screenshot capture, custom viewports, timeout budgets, "
            "explicit outcome handling, and optional HTML/GIF auxiliary artifacts."
        ),
        keywords=(
            "playwright",
            "timeout",
            "viewport",
            "capture",
            "partial",
            "full-page",
            "scroll",
            "gif",
            "motion",
            "html-snapshot",
        ),
        extras=("playwright", "motion"),
        example=(
            "result = await capture_screenshots_async("
            "'job', url, store_dir=Path('out'), partition_date=None, options=options)"
        ),
    ),
    Capability(
        slug="selenium-capture",
        task="Programmatic Selenium capture",
        preferred_import=(
            "from screenshot import capture_screenshots_async_selenium; "
            "from screenshot.models import CaptureOptions, ScreenshotOptions"
        ),
        summary=(
            "Use for Selenium-backed screenshot capture, Chrome/driver configuration, "
            "and backend parity checks."
        ),
        keywords=(
            "selenium",
            "chrome",
            "driver",
            "browser",
            "capture",
            "compatibility",
        ),
        extras=("selenium",),
        example=(
            "result = await capture_screenshots_async_selenium("
            "'job', url, store_dir=Path('out'), partition_date=None, options=options)"
        ),
    ),
    Capability(
        slug="screenshot-service",
        task="Batch orchestration with ScreenshotService",
        preferred_import=(
            "from screenshot import ScreenshotJob, ScreenshotOptions; "
            "from screenshot.backends import build_local_screenshot_service"
        ),
        summary=(
            "Use for ordered multi-job execution, cooperative cancellation, "
            "and aggregated batch outcomes."
        ),
        keywords=(
            "service",
            "batch",
            "job",
            "concurrency",
            "cancel",
            "ordered",
            "summary",
        ),
        example="batch = await service.capture_async(jobs, concurrency=2)",
    ),
    Capability(
        slug="storage-summary-integration",
        task="Storage backend / batch summary integration",
        preferred_import=(
            "from screenshot import LocalStorageBackend, CloudStorageBackend, AsyncStorageBackend; "
            "from screenshot.backends import build_local_screenshot_service"
        ),
        summary=(
            "Use for artifact persistence, summary writing, and integrating stored outputs "
            "with batch-level capture results."
        ),
        keywords=(
            "storage",
            "backend",
            "summary",
            "result",
            "upload",
            "batch",
            "artifacts",
        ),
        example=(
            "summary_path = LocalStorageBackend().write_json(Path('summary.json'), batch.to_dict())"
        ),
    ),
)


def find_capabilities(query: str) -> list[Capability]:
    """Return capabilities matching a free-text query."""

    normalized = query.strip().lower()
    if not normalized:
        return list(CAPABILITIES)

    terms = tuple(dict.fromkeys(normalized.split()))
    ranked: list[tuple[int, Capability]] = []
    for capability in CAPABILITIES:
        haystack = capability.searchable_text()
        score = sum(1 for term in terms if term in haystack)
        if normalized in haystack:
            score += len(terms)
        if score:
            ranked.append((score, capability))

    ranked.sort(key=lambda item: (-item[0], item[1].task))
    return [capability for _, capability in ranked]


__all__ = ["CAPABILITIES", "Capability", "find_capabilities"]
