#!/usr/bin/env python3
"""Mirror upstream OCI test images to GHCR without altering platform configs."""

from __future__ import annotations

import argparse
from dataclasses import dataclass
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
from typing import Any, Callable


DEFAULT_MANIFEST = Path(__file__).with_name("ci-image-mirrors.json")
DEFAULT_SOURCE_REPO = "https://github.com/superradcompany/microsandbox"
OCI_INDEX_MEDIA_TYPE = "application/vnd.oci.image.index.v1+json"
OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json"
DOCKER_MANIFEST_LIST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.list.v2+json"
SOURCE_ANNOTATION_KEY = "org.opencontainers.image.source"
DESCRIPTION_ANNOTATION_KEY = "org.opencontainers.image.description"

NAME_RE = re.compile(r"^[a-z0-9]+(?:[._/-][a-z0-9]+)*$")
TAG_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$")
DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$")

MISSING_TARGET_RE = re.compile(
    r"not found|manifest unknown|name unknown|denied|unauthorized|404|403",
    re.IGNORECASE,
)
RETRYABLE_REGISTRY_RE = re.compile(
    r"429|too many requests|toomanyrequests|rate limit|timeout|timed out|"
    r"connection reset|EOF|502|503|504|temporarily unavailable",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class MirrorTarget:
    """Single upstream tag mirrored to a GHCR destination tag."""

    name: str
    tag: str
    source_repo: str
    target_repo: str
    platforms: tuple[str, ...]

    @property
    def source_ref(self) -> str:
        return f"{self.source_repo}:{self.tag}"

    @property
    def target_ref(self) -> str:
        return f"{self.target_repo}:{self.tag}"


@dataclass(frozen=True)
class MirrorResult:
    """Outcome of syncing or validating one mirror target."""

    target: MirrorTarget
    action: str
    digests: dict[str, str]


CommandRunner = Callable[[list[str]], subprocess.CompletedProcess[str]]


def default_runner(cmd: list[str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(cmd, text=True, capture_output=True, check=False)


def parse_platform(spec: str) -> tuple[str, str, str | None]:
    parts = spec.strip().split("/")
    if len(parts) not in (2, 3) or any(not p for p in parts):
        raise ValueError(f"invalid platform spec: {spec!r}")
    return parts[0], parts[1], (parts[2] if len(parts) == 3 else None)


def load_manifest(path: Path) -> list[MirrorTarget]:
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError("mirror manifest must be a JSON object")

    registry = data.get("registry")
    namespace = data.get("namespace")
    platforms_raw = data.get("platforms")
    images = data.get("images")

    if not isinstance(registry, str) or not registry or "/" in registry:
        raise ValueError(f"invalid registry: {registry!r}")
    if not isinstance(namespace, str) or not NAME_RE.match(namespace):
        raise ValueError(f"invalid namespace: {namespace!r}")
    if not isinstance(platforms_raw, list) or not platforms_raw:
        raise ValueError("platforms must be a non-empty list")

    platforms: list[str] = []
    seen_platforms: set[str] = set()
    for p in platforms_raw:
        if not isinstance(p, str):
            raise ValueError(f"platform entry must be a string: {p!r}")
        parse_platform(p)
        if p in seen_platforms:
            raise ValueError(f"duplicate platform: {p!r}")
        seen_platforms.add(p)
        platforms.append(p)

    if not isinstance(images, list) or not images:
        raise ValueError("images must be a non-empty list")

    targets: list[MirrorTarget] = []
    seen_targets: set[str] = set()
    for entry in images:
        if not isinstance(entry, dict):
            raise ValueError("each image entry must be a JSON object")
        name = entry.get("name")
        source = entry.get("source")
        tags = entry.get("tags")
        if not isinstance(name, str) or not NAME_RE.match(name):
            raise ValueError(f"invalid image name: {name!r}")
        if not isinstance(source, str) or "/" not in source or ":" in source or "@" in source:
            raise ValueError(f"source must be a tagless registry/repo reference: {source!r}")
        if not isinstance(tags, list) or not tags:
            raise ValueError(f"tags for {name!r} must be a non-empty list")

        target_repo = f"{registry}/{namespace}/{name}"
        for tag in tags:
            if not isinstance(tag, str) or not TAG_RE.match(tag):
                raise ValueError(f"invalid tag {tag!r} for image {name!r}")
            target = MirrorTarget(
                name=name,
                tag=tag,
                source_repo=source,
                target_repo=target_repo,
                platforms=tuple(platforms),
            )
            if target.target_ref in seen_targets:
                raise ValueError(f"duplicate target reference: {target.target_ref}")
            seen_targets.add(target.target_ref)
            targets.append(target)

    return targets


def filter_targets(targets: list[MirrorTarget], selector: str) -> list[MirrorTarget]:
    selector = selector.strip()
    if not selector:
        return targets

    selected = [
        t for t in targets if selector in (t.name, f"{t.name}:{t.tag}", t.target_ref)
    ]
    if not selected:
        available = sorted({t.name for t in targets})
        raise ValueError(
            f"filter {selector!r} matched no mirror targets (available names: {', '.join(available)})"
        )
    return selected


def is_attestation_descriptor(descriptor: dict[str, Any]) -> bool:
    media_type = str(descriptor.get("mediaType", ""))
    if "attestation" in media_type:
        return True
    annotations = descriptor.get("annotations")
    if isinstance(annotations, dict):
        if annotations.get("vnd.docker.reference.type") == "attestation-manifest":
            return True
    platform = descriptor.get("platform")
    if isinstance(platform, dict) and platform.get("os") == "unknown":
        return True
    return False


def _platform_matches(
    descriptor_platform: dict[str, Any],
    want_os: str,
    want_arch: str,
    want_variant: str | None,
) -> tuple[bool, int]:
    """Return (matches, priority) where higher priority is a closer match."""
    if descriptor_platform.get("os") != want_os:
        return False, 0
    if descriptor_platform.get("architecture") != want_arch:
        return False, 0

    have_variant = descriptor_platform.get("variant") or None
    if want_variant is not None:
        return (have_variant == want_variant), 2

    if have_variant is None:
        return True, 2
    if want_arch == "arm64" and have_variant == "v8":
        return True, 1
    return False, 0


def extract_platform_manifests(
    index_doc: dict[str, Any],
    platforms: tuple[str, ...],
    ref: str,
) -> tuple[dict[str, str], bool]:
    """Return ({platform: digest}, supports_index_annotations)."""
    manifests = index_doc.get("manifests")
    if not isinstance(manifests, list) or not manifests:
        raise RuntimeError(f"{ref} did not resolve to a multi-platform manifest index")

    digests: dict[str, str] = {}
    media_types: dict[str, str] = {}
    for spec in platforms:
        want_os, want_arch, want_variant = parse_platform(spec)
        best_digest: str | None = None
        best_media_type: str = ""
        best_priority = -1
        for desc in manifests:
            if not isinstance(desc, dict) or is_attestation_descriptor(desc):
                continue
            plat = desc.get("platform")
            if not isinstance(plat, dict):
                continue
            matched, priority = _platform_matches(plat, want_os, want_arch, want_variant)
            if not matched:
                continue
            digest = desc.get("digest")
            if not isinstance(digest, str) or not DIGEST_RE.match(digest):
                raise RuntimeError(f"{ref} has invalid digest for {spec}: {digest!r}")
            if priority > best_priority:
                best_priority = priority
                best_digest = digest
                best_media_type = str(desc.get("mediaType", ""))

        if best_digest is None:
            raise RuntimeError(f"{ref} is missing required platform {spec}")
        digests[spec] = best_digest
        media_types[spec] = best_media_type

    # docker buildx imagetools create only supports --annotation when the source
    # platform manifests use OCI media types (Docker Schema 2 manifest lists do
    # not allow index annotations without rewriting the child manifests).
    supports_annotations = all(mt == OCI_MANIFEST_MEDIA_TYPE for mt in media_types.values())
    return digests, supports_annotations


def extract_platform_digests(
    index_doc: dict[str, Any],
    platforms: tuple[str, ...],
    ref: str,
) -> dict[str, str]:
    digests, _ = extract_platform_manifests(index_doc, platforms, ref)
    return digests


def run_with_retry(
    cmd: list[str],
    runner: CommandRunner,
    *,
    attempts: int = 3,
    base_delay: float = 2.0,
    sleeper: Callable[[float], None] = time.sleep,
) -> subprocess.CompletedProcess[str]:
    last: subprocess.CompletedProcess[str] | None = None
    for attempt in range(1, attempts + 1):
        result = runner(cmd)
        if result.returncode == 0:
            return result
        last = result
        combined = f"{result.stdout}\n{result.stderr}"
        if attempt < attempts and RETRYABLE_REGISTRY_RE.search(combined):
            delay = base_delay * (2 ** (attempt - 1))
            print(
                f"Retrying transient registry failure ({attempt}/{attempts}) in {delay:.1f}s: {' '.join(cmd)}",
                file=sys.stderr,
                flush=True,
            )
            sleeper(delay)
            continue
        return result
    assert last is not None
    return last


def inspect_raw_manifest(
    ref: str,
    runner: CommandRunner,
    *,
    allow_missing: bool = False,
    sleeper: Callable[[float], None] = time.sleep,
) -> dict[str, Any] | None:
    cmd = ["docker", "buildx", "imagetools", "inspect", "--raw", ref]
    proc = run_with_retry(cmd, runner, sleeper=sleeper)
    if proc.returncode != 0:
        err = (proc.stderr or proc.stdout).strip()
        if allow_missing and MISSING_TARGET_RE.search(err):
            return None
        raise RuntimeError(f"failed to inspect {ref}: {err}")
    try:
        doc = json.loads(proc.stdout)
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"invalid JSON from inspect {ref}: {exc}") from exc
    if not isinstance(doc, dict):
        raise RuntimeError(f"unexpected manifest payload for {ref}")
    return doc


def build_imagetools_create_cmd(
    target: MirrorTarget,
    digests: dict[str, str],
    source_repo_url: str,
    *,
    dry_run: bool,
    include_annotations: bool = True,
) -> list[str]:
    description = f"Mirror of {target.source_ref} for Microsandbox CI"
    cmd = [
        "docker",
        "buildx",
        "imagetools",
        "create",
        "--tag",
        target.target_ref,
    ]
    if include_annotations:
        cmd.extend(
            [
                "--annotation",
                f"index:{SOURCE_ANNOTATION_KEY}={source_repo_url}",
                "--annotation",
                f"index:{DESCRIPTION_ANNOTATION_KEY}={description}",
            ]
        )
    if dry_run:
        cmd.append("--dry-run")
    for spec in target.platforms:
        cmd.append(f"{target.source_repo}@{digests[spec]}")
    return cmd


def verify_index_document(
    index_doc: dict[str, Any],
    target: MirrorTarget,
    expected_digests: dict[str, str],
    source_repo_url: str,
    *,
    expect_annotations: bool = True,
) -> None:
    media_type = index_doc.get("mediaType")
    allowed_media_types = (
        (OCI_INDEX_MEDIA_TYPE,)
        if expect_annotations
        else (OCI_INDEX_MEDIA_TYPE, DOCKER_MANIFEST_LIST_MEDIA_TYPE)
    )
    if media_type not in allowed_media_types:
        raise RuntimeError(
            f"{target.target_ref} has mediaType {media_type!r}, expected one of {allowed_media_types!r}"
        )

    actual_digests = extract_platform_digests(index_doc, target.platforms, target.target_ref)
    if actual_digests != expected_digests:
        raise RuntimeError(
            f"{target.target_ref} digests {actual_digests} do not match upstream {expected_digests}"
        )

    if expect_annotations:
        annotations = index_doc.get("annotations") or {}
        actual_source = annotations.get(SOURCE_ANNOTATION_KEY)
        if actual_source != source_repo_url:
            raise RuntimeError(
                f"{target.target_ref} missing {SOURCE_ANNOTATION_KEY}={source_repo_url!r} "
                f"(got {actual_source!r})"
            )


def destination_is_current(
    target: MirrorTarget,
    expected_digests: dict[str, str],
    source_repo_url: str,
    runner: CommandRunner,
    *,
    expect_annotations: bool = True,
    sleeper: Callable[[float], None] = time.sleep,
) -> bool:
    doc = inspect_raw_manifest(target.target_ref, runner, allow_missing=True, sleeper=sleeper)
    if doc is None:
        return False
    try:
        verify_index_document(
            doc,
            target,
            expected_digests,
            source_repo_url,
            expect_annotations=expect_annotations,
        )
    except RuntimeError:
        return False
    return True


def sync_target(
    target: MirrorTarget,
    *,
    source_repo_url: str,
    dry_run: bool,
    force: bool,
    runner: CommandRunner = default_runner,
    sleeper: Callable[[float], None] = time.sleep,
) -> MirrorResult:
    upstream_doc = inspect_raw_manifest(target.source_ref, runner, sleeper=sleeper)
    assert upstream_doc is not None
    upstream_digests, supports_annotations = extract_platform_manifests(
        upstream_doc, target.platforms, target.source_ref
    )

    if dry_run:
        cmd = build_imagetools_create_cmd(
            target,
            upstream_digests,
            source_repo_url,
            dry_run=True,
            include_annotations=supports_annotations,
        )
        proc = run_with_retry(cmd, runner, sleeper=sleeper)
        if proc.returncode != 0:
            err = (proc.stderr or proc.stdout).strip()
            raise RuntimeError(f"dry-run failed for {target.target_ref}: {err}")
        dry_doc = json.loads(proc.stdout)
        verify_index_document(
            dry_doc,
            target,
            upstream_digests,
            source_repo_url,
            expect_annotations=supports_annotations,
        )
        print(f"DRY-RUN  {target.source_ref} -> {target.target_ref}", flush=True)
        return MirrorResult(target=target, action="dry-run", digests=upstream_digests)

    if not force and destination_is_current(
        target,
        upstream_digests,
        source_repo_url,
        runner,
        expect_annotations=supports_annotations,
        sleeper=sleeper,
    ):
        print(f"CURRENT  {target.target_ref} (unchanged)", flush=True)
        return MirrorResult(target=target, action="up-to-date", digests=upstream_digests)

    cmd = build_imagetools_create_cmd(
        target,
        upstream_digests,
        source_repo_url,
        dry_run=False,
        include_annotations=supports_annotations,
    )
    proc = run_with_retry(cmd, runner, sleeper=sleeper)
    if proc.returncode != 0:
        err = (proc.stderr or proc.stdout).strip()
        raise RuntimeError(f"failed to publish {target.target_ref}: {err}")

    published_doc = inspect_raw_manifest(target.target_ref, runner, sleeper=sleeper)
    assert published_doc is not None
    verify_index_document(
        published_doc,
        target,
        upstream_digests,
        source_repo_url,
        expect_annotations=supports_annotations,
    )
    print(f"PUBLISH  {target.source_ref} -> {target.target_ref}", flush=True)
    return MirrorResult(target=target, action="published", digests=upstream_digests)


def format_step_summary(results: list[MirrorResult], *, dry_run: bool) -> str:
    heading = "## CI Image Mirrors (Dry Run)" if dry_run else "## CI Image Mirrors"
    lines = [
        heading,
        "",
        "| Target | Source | Status | `linux/amd64` | `linux/arm64` |",
        "| --- | --- | --- | --- | --- |",
    ]
    for item in results:
        amd64 = item.digests.get("linux/amd64", "-")[:19]
        arm64 = item.digests.get("linux/arm64", "-")[:19]
        lines.append(
            f"| `{item.target.target_ref}` | `{item.target.source_ref}` | "
            f"{item.action} | `{amd64}` | `{arm64}` |"
        )
    if not dry_run and any(r.action == "published" for r in results):
        packages = sorted({r.target.target_repo for r in results})
        lines.extend(
            [
                "",
                "> Note: Brand-new GHCR packages start private by default. After the first "
                "publish, set package visibility to **Public** once for each package:",
                *[f"> - `{pkg}`" for pkg in packages],
            ]
        )
    return "\n".join(lines) + "\n"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--manifest",
        type=Path,
        default=DEFAULT_MANIFEST,
        help="Path to the mirror catalog JSON file.",
    )
    parser.add_argument(
        "--source-repo",
        default=os.environ.get("MSB_MIRROR_SOURCE_REPO", DEFAULT_SOURCE_REPO),
        help="Repository URL for the org.opencontainers.image.source index annotation.",
    )
    parser.add_argument(
        "--filter",
        default="",
        help="Optional image name, name:tag, or full target ref to sync.",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Publish even when destination digests already match upstream.",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Inspect upstream images and validate imagetools create without pushing.",
    )
    parser.add_argument(
        "--validate-only",
        action="store_true",
        help="Validate the local manifest schema without contacting registries.",
    )
    args = parser.parse_args(argv)

    try:
        targets = filter_targets(load_manifest(args.manifest), args.filter)
        if args.validate_only:
            print(f"Manifest valid: {len(targets)} target(s) in {args.manifest}")
            return 0

        results = [
            sync_target(
                target,
                source_repo_url=args.source_repo,
                dry_run=args.dry_run,
                force=args.force,
            )
            for target in targets
        ]

        summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
        if summary_path:
            with Path(summary_path).open("a", encoding="utf-8") as fh:
                fh.write(format_step_summary(results, dry_run=args.dry_run))
    except (OSError, ValueError, RuntimeError) as error:
        print(f"::error::{error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
