#!/usr/bin/env python3
"""Read official Claude Code release metadata; never execute or install it."""
import argparse
import datetime
import hashlib
import json
from pathlib import Path
import re
import sys
import urllib.request

BASE = "https://downloads.claude.ai/claude-code-releases"
PLATFORMS = ("darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64",
             "linux-arm64-musl", "linux-x64-musl", "win32-arm64", "win32-x64")
VERSION = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+\Z")


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "claude-code-customization/1"})
    with urllib.request.urlopen(request, timeout=30) as response:
        data = response.read(1024 * 1024 + 1)
    if len(data) > 1024 * 1024:
        raise ValueError("Release metadata exceeds 1 MiB")
    return data


def release_info(version, platform, binary=None, reader=fetch):
    if platform not in PLATFORMS:
        raise ValueError("Unsupported platform")
    if version not in ("latest", "stable") and not VERSION.fullmatch(version):
        raise ValueError("Version must be latest, stable or X.Y.Z")
    resolved = reader(f"{BASE}/{version}").decode("utf-8").strip() if version in ("latest", "stable") else version
    if not VERSION.fullmatch(resolved):
        raise ValueError("Invalid version from official channel")
    manifest_url = f"{BASE}/{resolved}/manifest.json"
    manifest = json.loads(reader(manifest_url))
    if manifest.get("version") != resolved:
        raise ValueError("Manifest version mismatch")
    entry = manifest.get("platforms", {}).get(platform)
    if not isinstance(entry, dict):
        raise ValueError("Missing platform in manifest")
    checksum, size = entry.get("checksum"), entry.get("size")
    if not isinstance(checksum, str) or not re.fullmatch(r"[0-9a-fA-F]{64}", checksum):
        raise ValueError("Invalid SHA-256 in manifest")
    if type(size) is not int or size <= 0:
        raise ValueError("Invalid size in manifest")
    executable = "claude.exe" if platform.startswith("win32-") else "claude"
    if entry.get("binary") != executable:
        raise ValueError("Unexpected binary name in manifest")
    result = {
        "requestedVersion": version, "version": resolved, "platform": platform,
        "checkedAtUtc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "manifestUrl": manifest_url, "signatureUrl": manifest_url + ".sig",
        "binaryUrl": f"{BASE}/{resolved}/{platform}/{executable}",
        "sha256": checksum.lower(), "size": size, "signatureVerified": False,
        "verificationScope": "Official HTTPS metadata only; verify manifest GPG before building",
    }
    if binary is not None:
        digest = hashlib.sha256()
        actual_size = 0
        with Path(binary).open("rb") as stream:
            for block in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(block)
                actual_size += len(block)
        actual_hash = digest.hexdigest()
        result["localBinary"] = {
            "sha256": actual_hash, "size": actual_size,
            "matchesManifest": actual_hash == checksum.lower() and actual_size == size,
        }
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--version", default="latest", help="latest, stable or X.Y.Z")
    parser.add_argument("--platform", required=True, choices=PLATFORMS)
    parser.add_argument("--binary", type=Path, help="Optional local file to hash; never executed")
    args = parser.parse_args()
    try:
        result = release_info(args.version, args.platform, args.binary)
    except (ValueError, OSError, TypeError, AttributeError) as error:
        parser.exit(2, f"Error: {error}\n")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 1 if result.get("localBinary", {}).get("matchesManifest") is False else 0


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