"""Shared helpers for screenshot CLI commands."""

from __future__ import annotations

from dataclasses import dataclass, field

from ._models_artifacts import ScreenshotArtifactsRequest
from ._shared.cli.options import build_options
from ._shared.cli.parser import load_cli_inputs
from ._shared.cli.schema import ScreenshotCliArgs
from ._shared.cli.utils import derive_job_id
from ._shared.cli.validator import validate_backend_choice
from .models import ScreenshotOptions


@dataclass(frozen=True, slots=True)
class ResolvedJobSpec:
    """Internal normalized CLI job spec."""

    job_id: str
    url: str
    partition_date: str | None
    metadata: dict[str, object]
    options: ScreenshotOptions
    backend: str
    artifacts: ScreenshotArtifactsRequest = field(default_factory=ScreenshotArtifactsRequest)


def collect_job_specs(args: ScreenshotCliArgs) -> list[ResolvedJobSpec]:
    """Return normalized screenshot job specs from CLI arguments."""

    backend = (args.backend or "playwright").strip().lower()
    records, css_snippets, js_snippets = load_cli_inputs(args)

    specs: list[ResolvedJobSpec] = []
    for record in records:
        options = build_options(
            args=args,
            css_snippets=css_snippets,
            js_snippets=js_snippets,
            overrides=record.options_override,
        )
        validate_backend_choice(backend, options, record.artifacts)

        metadata = dict(record.metadata)
        metadata.setdefault("backend", backend)

        specs.append(
            ResolvedJobSpec(
                job_id=record.job_id,
                url=record.url,
                partition_date=record.partition_date,
                artifacts=record.artifacts,
                metadata=metadata,
                options=options,
                backend=backend,
            )
        )

    return specs


def spec_to_api_payload(spec: ResolvedJobSpec) -> dict[str, object]:
    """Convert a job spec into the payload expected by the screenshot service."""

    payload: dict[str, object] = {
        "job_id": spec.job_id,
        "url": spec.url,
        "partition_date": spec.partition_date,
        "metadata": dict(spec.metadata),
        "options": serialize_options(spec.options),
    }
    backend_value = spec.backend
    if backend_value:
        payload["backend"] = backend_value
    artifacts_payload = spec.artifacts.to_dict()
    if any(value is not None for value in artifacts_payload.values()):
        payload["artifacts"] = artifacts_payload
    return payload


def serialize_options(options: ScreenshotOptions) -> dict[str, object]:
    """Serialize ScreenshotOptions to simple types for JSON payloads."""

    return options.to_dict()


__all__ = [
    "collect_job_specs",
    "spec_to_api_payload",
    "serialize_options",
    "derive_job_id",
    "ScreenshotCliArgs",
]
