import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch


SPEC = importlib.util.spec_from_file_location(
    "mirror_ci_images", Path(__file__).with_name("mirror-ci-images.py")
)
mirror = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = mirror
SPEC.loader.exec_module(mirror)

AMD64_DIGEST = "sha256:" + "a" * 64
ARM64_DIGEST = "sha256:" + "b" * 64
ATTEST_DIGEST = "sha256:" + "c" * 64
SOURCE_REPO = "https://github.com/superradcompany/microsandbox"


def make_index(
    *,
    media_type: str = mirror.OCI_INDEX_MEDIA_TYPE,
    child_media_type: str = mirror.OCI_MANIFEST_MEDIA_TYPE,
    amd64_digest: str = AMD64_DIGEST,
    arm64_digest: str = ARM64_DIGEST,
    arm64_variant: str | None = "v8",
    include_attestation: bool = True,
    annotations: dict[str, str] | None = None,
) -> dict:
    arm64_platform = {"os": "linux", "architecture": "arm64"}
    if arm64_variant is not None:
        arm64_platform["variant"] = arm64_variant
    manifests = [
        {
            "mediaType": child_media_type,
            "digest": amd64_digest,
            "platform": {"os": "linux", "architecture": "amd64"},
        },
        {
            "mediaType": child_media_type,
            "digest": arm64_digest,
            "platform": arm64_platform,
        },
    ]
    if include_attestation:
        manifests.append(
            {
                "mediaType": "application/vnd.oci.image.manifest.v1+json",
                "digest": ATTEST_DIGEST,
                "platform": {"os": "unknown", "architecture": "unknown"},
                "annotations": {"vnd.docker.reference.type": "attestation-manifest"},
            }
        )
    doc = {"schemaVersion": 2, "mediaType": media_type, "manifests": manifests}
    if annotations is not None:
        doc["annotations"] = annotations
    return doc


def completed(returncode: int = 0, stdout: str = "", stderr: str = "") -> subprocess.CompletedProcess[str]:
    return subprocess.CompletedProcess(args=["docker"], returncode=returncode, stdout=stdout, stderr=stderr)


class ManifestValidationTests(unittest.TestCase):
    def test_checked_in_manifest_is_valid_and_complete(self):
        targets = mirror.load_manifest(mirror.DEFAULT_MANIFEST)
        target_refs = {t.target_ref for t in targets}
        self.assertEqual(
            target_refs,
            {
                "ghcr.io/superradcompany/ci/alpine:latest",
                "ghcr.io/superradcompany/ci/alpine:3.20",
                "ghcr.io/superradcompany/ci/alpine:3.21",
                "ghcr.io/superradcompany/ci/alpine:3.22",
                "ghcr.io/superradcompany/ci/curl:latest",
                "ghcr.io/superradcompany/ci/node:alpine",
                "ghcr.io/superradcompany/ci/python:3.12-alpine",
                "ghcr.io/superradcompany/ci/python:3.13-alpine",
                "ghcr.io/superradcompany/ci/python:3.13-alpine3.22",
            },
        )
        for t in targets:
            self.assertEqual(t.platforms, ("linux/amd64", "linux/arm64"))

    def test_rejects_duplicate_target_tags(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "manifest.json"
            path.write_text(
                json.dumps(
                    {
                        "registry": "ghcr.io",
                        "namespace": "superradcompany/ci",
                        "platforms": ["linux/amd64", "linux/arm64"],
                        "images": [
                            {"name": "alpine", "source": "docker.io/library/alpine", "tags": ["3.20", "3.20"]}
                        ],
                    }
                ),
                encoding="utf-8",
            )
            with self.assertRaisesRegex(ValueError, "duplicate target"):
                mirror.load_manifest(path)

    def test_rejects_tagged_source(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "manifest.json"
            path.write_text(
                json.dumps(
                    {
                        "registry": "ghcr.io",
                        "namespace": "superradcompany/ci",
                        "platforms": ["linux/amd64"],
                        "images": [
                            {"name": "alpine", "source": "docker.io/library/alpine:3.20", "tags": ["3.20"]}
                        ],
                    }
                ),
                encoding="utf-8",
            )
            with self.assertRaisesRegex(ValueError, "tagless"):
                mirror.load_manifest(path)

    def test_filter_targets_by_name_tag_or_full_ref(self):
        targets = mirror.load_manifest(mirror.DEFAULT_MANIFEST)
        self.assertEqual(len(mirror.filter_targets(targets, "")), len(targets))
        self.assertEqual(len(mirror.filter_targets(targets, "alpine")), 4)
        self.assertEqual(
            [t.target_ref for t in mirror.filter_targets(targets, "alpine:3.20")],
            ["ghcr.io/superradcompany/ci/alpine:3.20"],
        )
        self.assertEqual(
            [t.target_ref for t in mirror.filter_targets(targets, "ghcr.io/superradcompany/ci/curl:latest")],
            ["ghcr.io/superradcompany/ci/curl:latest"],
        )
        with self.assertRaisesRegex(ValueError, "matched no mirror targets"):
            mirror.filter_targets(targets, "nonexistent")


class PlatformExtractionTests(unittest.TestCase):
    def test_extracts_amd64_and_arm64_v8_ignoring_attestations(self):
        doc = make_index(
            media_type="application/vnd.docker.distribution.manifest.list.v2+json",
            arm64_variant="v8",
            include_attestation=True,
        )
        digests = mirror.extract_platform_digests(doc, ("linux/amd64", "linux/arm64"), "src:tag")
        self.assertEqual(
            digests,
            {"linux/amd64": AMD64_DIGEST, "linux/arm64": ARM64_DIGEST},
        )

    def test_rejects_missing_required_platform(self):
        doc = {
            "mediaType": mirror.OCI_INDEX_MEDIA_TYPE,
            "manifests": [
                {
                    "mediaType": "application/vnd.oci.image.manifest.v1+json",
                    "digest": AMD64_DIGEST,
                    "platform": {"os": "linux", "architecture": "amd64"},
                }
            ],
        }
        with self.assertRaisesRegex(RuntimeError, "missing required platform linux/arm64"):
            mirror.extract_platform_digests(doc, ("linux/amd64", "linux/arm64"), "src:tag")


class SyncBehaviorTests(unittest.TestCase):
    def setUp(self):
        self.target = mirror.MirrorTarget(
            name="alpine",
            tag="3.20",
            source_repo="docker.io/library/alpine",
            target_repo="ghcr.io/superradcompany/ci/alpine",
            platforms=("linux/amd64", "linux/arm64"),
        )

    def test_dry_run_validates_imagetools_create_output_without_push(self):
        calls = []

        def fake_runner(cmd):
            calls.append(cmd)
            if cmd[:4] == ["docker", "buildx", "imagetools", "inspect"]:
                return completed(0, json.dumps(make_index()))
            if cmd[:4] == ["docker", "buildx", "imagetools", "create"]:
                self.assertIn("--dry-run", cmd)
                self.assertIn(f"index:{mirror.SOURCE_ANNOTATION_KEY}={SOURCE_REPO}", cmd)
                return completed(
                    0,
                    json.dumps(
                        make_index(
                            include_attestation=False,
                            annotations={mirror.SOURCE_ANNOTATION_KEY: SOURCE_REPO},
                        )
                    ),
                )
            raise AssertionError(f"unexpected command: {cmd}")

        result = mirror.sync_target(
            self.target,
            source_repo_url=SOURCE_REPO,
            dry_run=True,
            force=False,
            runner=fake_runner,
            sleeper=lambda _: None,
        )
        self.assertEqual(result.action, "dry-run")
        self.assertEqual(len(calls), 2)

    def test_docker_schema2_manifest_list_omits_index_annotations(self):
        curl_target = mirror.MirrorTarget(
            name="curl",
            tag="latest",
            source_repo="quay.io/curl/curl",
            target_repo="ghcr.io/superradcompany/ci/curl",
            platforms=("linux/amd64", "linux/arm64"),
        )
        docker_list = make_index(
            media_type=mirror.DOCKER_MANIFEST_LIST_MEDIA_TYPE,
            child_media_type="application/vnd.docker.distribution.manifest.v2+json",
            include_attestation=False,
        )

        def fake_runner(cmd):
            if cmd[:4] == ["docker", "buildx", "imagetools", "inspect"]:
                return completed(0, json.dumps(docker_list))
            if cmd[:4] == ["docker", "buildx", "imagetools", "create"]:
                self.assertIn("--dry-run", cmd)
                self.assertNotIn("--annotation", cmd)
                return completed(0, json.dumps(docker_list))
            raise AssertionError(f"unexpected command: {cmd}")

        result = mirror.sync_target(
            curl_target,
            source_repo_url=SOURCE_REPO,
            dry_run=True,
            force=False,
            runner=fake_runner,
            sleeper=lambda _: None,
        )
        self.assertEqual(result.action, "dry-run")

    def test_publish_skips_when_destination_matches_upstream(self):
        calls = []

        def fake_runner(cmd):
            calls.append(cmd)
            if cmd[-1] == self.target.source_ref:
                return completed(0, json.dumps(make_index()))
            if cmd[-1] == self.target.target_ref:
                return completed(
                    0,
                    json.dumps(
                        make_index(
                            include_attestation=False,
                            annotations={mirror.SOURCE_ANNOTATION_KEY: SOURCE_REPO},
                        )
                    ),
                )
            raise AssertionError(f"unexpected command: {cmd}")

        result = mirror.sync_target(
            self.target,
            source_repo_url=SOURCE_REPO,
            dry_run=False,
            force=False,
            runner=fake_runner,
            sleeper=lambda _: None,
        )
        self.assertEqual(result.action, "up-to-date")
        self.assertEqual(len(calls), 2)

    def test_publish_handles_missing_ghcr_package_and_verifies_result(self):
        calls = []
        published = False

        def fake_runner(cmd):
            nonlocal published
            calls.append(cmd)
            if cmd[:4] == ["docker", "buildx", "imagetools", "inspect"]:
                if cmd[-1] == self.target.source_ref:
                    return completed(0, json.dumps(make_index()))
                if not published:
                    return completed(1, stderr="ERROR: ghcr.io/superradcompany/ci/alpine:3.20: denied")
                return completed(
                    0,
                    json.dumps(
                        make_index(
                            include_attestation=False,
                            annotations={mirror.SOURCE_ANNOTATION_KEY: SOURCE_REPO},
                        )
                    ),
                )
            if cmd[:4] == ["docker", "buildx", "imagetools", "create"]:
                self.assertNotIn("--dry-run", cmd)
                self.assertEqual(
                    cmd[-2:],
                    [
                        f"{self.target.source_repo}@{AMD64_DIGEST}",
                        f"{self.target.source_repo}@{ARM64_DIGEST}",
                    ],
                )
                published = True
                return completed(0)
            raise AssertionError(f"unexpected command: {cmd}")

        result = mirror.sync_target(
            self.target,
            source_repo_url=SOURCE_REPO,
            dry_run=False,
            force=False,
            runner=fake_runner,
            sleeper=lambda _: None,
        )
        self.assertEqual(result.action, "published")
        self.assertEqual(len(calls), 4)

    def test_force_publishes_without_destination_precheck(self):
        calls = []

        def fake_runner(cmd):
            calls.append(cmd)
            if cmd[:4] == ["docker", "buildx", "imagetools", "inspect"]:
                if cmd[-1] == self.target.source_ref:
                    return completed(0, json.dumps(make_index()))
                return completed(
                    0,
                    json.dumps(
                        make_index(
                            include_attestation=False,
                            annotations={mirror.SOURCE_ANNOTATION_KEY: SOURCE_REPO},
                        )
                    ),
                )
            if cmd[:4] == ["docker", "buildx", "imagetools", "create"]:
                return completed(0)
            raise AssertionError(f"unexpected command: {cmd}")

        result = mirror.sync_target(
            self.target,
            source_repo_url=SOURCE_REPO,
            dry_run=False,
            force=True,
            runner=fake_runner,
            sleeper=lambda _: None,
        )
        self.assertEqual(result.action, "published")
        self.assertEqual(len(calls), 3)

    def test_retries_transient_429_failures(self):
        attempts = 0
        sleeps = []

        def fake_runner(_cmd):
            nonlocal attempts
            attempts += 1
            if attempts < 3:
                return completed(1, stderr="429 Too Many Requests")
            return completed(0, stdout="ok")

        proc = mirror.run_with_retry(["docker"], fake_runner, sleeper=sleeps.append)
        self.assertEqual(proc.returncode, 0)
        self.assertEqual(attempts, 3)
        self.assertEqual(sleeps, [2.0, 4.0])

    def test_step_summary_includes_visibility_note_when_published(self):
        res = [
            mirror.MirrorResult(
                target=self.target,
                action="published",
                digests={"linux/amd64": AMD64_DIGEST, "linux/arm64": ARM64_DIGEST},
            )
        ]
        summary = mirror.format_step_summary(res, dry_run=False)
        self.assertIn("ghcr.io/superradcompany/ci/alpine:3.20", summary)
        self.assertIn("Public", summary)

        dry_summary = mirror.format_step_summary(res, dry_run=True)
        self.assertIn("Dry Run", dry_summary)
        self.assertNotIn("Public", dry_summary)

    def test_main_validate_only_succeeds(self):
        with patch.dict(os.environ, {}, clear=True):
            rc = mirror.main(["--validate-only"])
        self.assertEqual(rc, 0)


if __name__ == "__main__":
    unittest.main()
