#!/usr/bin/env python3
"""Verify and install a public Yunfu Skills bundle without executing its contents."""

import argparse
import ctypes
import errno
import hashlib
import ipaddress
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import sys
import tempfile
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
import zipfile

MAX_DOWNLOAD = 20 * 1024 * 1024
MAX_INDEX = 1024 * 1024
MAX_EXPANDED = 40 * 1024 * 1024
MAX_FILES = 3000
MAX_RATIO = 150
SKILL_ID = re.compile(r"yunfu-[a-z0-9]+(?:-[a-z0-9]+)*\Z")
DIGEST = re.compile(r"[a-fA-F0-9]{64}\Z")


class InstallError(Exception):
    pass


def origin(url):
    parsed = urlsplit(url)
    try:
        port = parsed.port or (443 if parsed.scheme == "https" else 80)
    except ValueError as exc:
        raise InstallError("Invalid URL port") from exc
    if parsed.username is not None or parsed.password is not None:
        raise InstallError("URLs must not contain credentials")
    return parsed.scheme.lower(), (parsed.hostname or "").lower(), port


def base_origin(value):
    parsed = urlsplit(value)
    scheme, host, port = origin(value)
    if not host or parsed.path not in ("", "/") or parsed.query or parsed.fragment:
        raise InstallError("--base-url must be an origin, without a path or query")
    loopback = host == "localhost"
    try:
        loopback = loopback or ipaddress.ip_address(host).is_loopback
    except ValueError:
        pass
    if scheme != "https" and not (scheme == "http" and loopback):
        raise InstallError("HTTPS is required; HTTP is allowed only for loopback")
    bracketed = "[" + host + "]" if ":" in host else host
    default = 443 if scheme == "https" else 80
    return scheme + "://" + bracketed + (":" + str(port) if port != default else "")


class SameOriginRedirect(HTTPRedirectHandler):
    def __init__(self, allowed_origin):
        self.allowed_origin = allowed_origin

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        destination = urljoin(req.full_url, newurl)
        if origin(destination) != self.allowed_origin:
            raise InstallError("Refused a redirect to another origin")
        return super().redirect_request(req, fp, code, msg, headers, destination)


def fetch(opener, url, limit):
    request = Request(url, headers={"User-Agent": "Yunfu-Skills-Installer/1", "Accept": "*/*"})
    with opener.open(request, timeout=30) as response:
        if origin(response.geturl()) != origin(url):
            raise InstallError("Download changed origin")
        length = response.headers.get("Content-Length")
        if length and length.isdigit() and int(length) > limit:
            raise InstallError("Download exceeds its size limit")
        parts = []
        total = 0
        while True:
            block = response.read(min(65536, limit - total + 1))
            if not block:
                return b"".join(parts)
            total += len(block)
            if total > limit:
                raise InstallError("Download exceeds its size limit")
            parts.append(block)


def parse_index(data, public=False):
    try:
        value = json.loads(data)
    except (ValueError, UnicodeError) as exc:
        raise InstallError("Invalid Skills index JSON") from exc
    if not isinstance(value, dict) or not isinstance(value.get("version"), str) or not value["version"]:
        raise InstallError("Skills index must include a version")
    entries = value.get("skills")
    if not isinstance(entries, list) or not entries or len(entries) > MAX_FILES:
        raise InstallError("Skills index must include a nonempty skills list")
    ids = []
    for entry in entries:
        skill = entry.get("id") if isinstance(entry, dict) else None
        if not isinstance(skill, str) or len(skill) > 100 or not SKILL_ID.fullmatch(skill):
            raise InstallError("Invalid skill ID in index")
        ids.append(skill)
    if len(set(ids)) != len(ids):
        raise InstallError("Duplicate skill ID in index")
    if public:
        if value.get("download") != "/skills/all.zip":
            raise InstallError("Unexpected bundle download path")
        if not isinstance(value.get("sha256"), str) or not DIGEST.fullmatch(value["sha256"]):
            raise InstallError("Skills index must include a SHA256 digest")
    return value, set(ids)


def validate_archive(archive, expected=None):
    entries = archive.infolist()
    if not entries or len(entries) > MAX_FILES:
        raise InstallError("ZIP contains too many files or is empty")
    seen = set()
    skill_dirs = set()
    total = 0
    for entry in entries:
        name = entry.filename
        path = PurePosixPath(name)
        stripped = name[:-1] if name.endswith("/") else name
        if (not stripped or "\\" in name or "\x00" in name or len(name) > 500
                or path.is_absolute() or any(part in ("", ".", "..") for part in stripped.split("/"))
                or ":" in path.parts[0]):
            raise InstallError("Unsafe ZIP path: " + repr(name))
        if stripped in seen:
            raise InstallError("Duplicate ZIP path: " + repr(name))
        seen.add(stripped)
        mode = entry.external_attr >> 16
        kind = stat.S_IFMT(mode)
        if stat.S_ISLNK(mode) or kind not in (0, stat.S_IFREG, stat.S_IFDIR):
            raise InstallError("ZIP links and special files are not allowed")
        if kind == stat.S_IFDIR and not entry.is_dir():
            raise InstallError("Invalid ZIP directory entry")
        if entry.flag_bits & 1:
            raise InstallError("Encrypted ZIP files are not supported")
        if entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
            raise InstallError("Unsupported ZIP compression")
        root = path.parts[0]
        if SKILL_ID.fullmatch(root):
            skill_dirs.add(root)
            if len(path.parts) == 1 and not entry.is_dir():
                raise InstallError("Skill root must be a directory")
        elif name not in ("README.md", "index.json"):
            raise InstallError("Unexpected top-level ZIP entry: " + repr(name))
        total += entry.file_size
        if entry.file_size < 0 or total > MAX_EXPANDED:
            raise InstallError("Expanded ZIP exceeds 40 MB")
        if entry.file_size > max(1, entry.compress_size) * MAX_RATIO:
            raise InstallError("Suspicious ZIP compression ratio")
    if not skill_dirs or "index.json" not in seen:
        raise InstallError("ZIP is missing skills or index.json")
    if archive.getinfo("index.json").file_size > MAX_INDEX:
        raise InstallError("Embedded index exceeds its size limit")
    embedded, embedded_ids = parse_index(archive.read("index.json"))
    if embedded_ids != skill_dirs or (expected and embedded_ids != expected[1]):
        raise InstallError("ZIP skill directories do not match the index")
    if expected and embedded["version"] != expected[0]["version"]:
        raise InstallError("ZIP version does not match the public index")
    for skill in skill_dirs:
        marker = skill + "/SKILL.md"
        if marker not in seen or archive.getinfo(marker).is_dir():
            raise InstallError("Skill is missing SKILL.md: " + skill)
    return entries, sorted(skill_dirs)


def rename_without_overwrite(source, destination):
    """Use the platform's atomic no-replace operation, including concurrent installs."""
    if os.name == "nt":
        os.rename(source, destination)  # Windows rejects an existing destination.
        return
    libc = ctypes.CDLL(None, use_errno=True)
    if sys.platform == "darwin":
        operation = libc.renamex_np
        operation.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
        operation.restype = ctypes.c_int
        result = operation(os.fsencode(source), os.fsencode(destination), 4)  # RENAME_EXCL
    elif sys.platform.startswith("linux") and hasattr(libc, "renameat2"):
        operation = libc.renameat2
        operation.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
        operation.restype = ctypes.c_int
        result = operation(-100, os.fsencode(source), -100, os.fsencode(destination), 1)  # RENAME_NOREPLACE
    else:
        raise InstallError("This platform does not support atomic installation without overwriting")
    if result:
        code = ctypes.get_errno()
        if code == errno.EEXIST:
            raise FileExistsError(code, os.strerror(code), str(destination))
        raise OSError(code, os.strerror(code), str(destination))


def install(args):
    expected = None
    if args.bundle:
        if not args.sha256 or not DIGEST.fullmatch(args.sha256):
            raise InstallError("Offline installation requires --sha256 with the expected digest")
        bundle = Path(args.bundle).expanduser()
        if bundle.stat().st_size > MAX_DOWNLOAD:
            raise InstallError("Bundle exceeds 20 MB")
        with bundle.open("rb") as stream:
            data = stream.read(MAX_DOWNLOAD + 1)
        digest = args.sha256.lower()
    else:
        if args.sha256:
            raise InstallError("--sha256 is only used with --bundle")
        base = base_origin(args.base_url)
        opener = build_opener(SameOriginRedirect(origin(base)))
        expected = parse_index(fetch(opener, base + "/skills/index.json", MAX_INDEX), public=True)
        data = fetch(opener, base + expected[0]["download"], MAX_DOWNLOAD)
        digest = expected[0]["sha256"].lower()
    if len(data) > MAX_DOWNLOAD:
        raise InstallError("Bundle exceeds 20 MB")
    if hashlib.sha256(data).hexdigest() != digest:
        raise InstallError("Bundle SHA256 verification failed")
    # Verify everything before creating the destination or installing any skill.
    import io
    with zipfile.ZipFile(io.BytesIO(data)) as archive:
        entries, skills = validate_archive(archive, expected)
        target = Path(args.target).expanduser().absolute()
        if target.is_symlink():
            raise InstallError("Installation target must not be a symbolic link")
        target.mkdir(parents=True, exist_ok=True)
        if not target.is_dir():
            raise InstallError("Installation target must be a directory")
        installed = []
        skipped = []
        # Same filesystem as target: each skill becomes visible in one atomic move.
        with tempfile.TemporaryDirectory(prefix=".yunfu-skills-", dir=target) as scratch:
            staging = Path(scratch)
            expanded = 0
            for entry in entries:
                destination = staging.joinpath(*PurePosixPath(entry.filename).parts)
                if entry.is_dir():
                    destination.mkdir(parents=True, exist_ok=True)
                    continue
                destination.parent.mkdir(parents=True, exist_ok=True)
                with archive.open(entry) as source, destination.open("xb") as output:
                    count = 0
                    while True:
                        block = source.read(65536)
                        if not block:
                            break
                        count += len(block)
                        expanded += len(block)
                        if count > entry.file_size or expanded > MAX_EXPANDED:
                            raise InstallError("ZIP expanded beyond its declared size")
                        output.write(block)
                if count != entry.file_size:
                    raise InstallError("ZIP file size did not match metadata")
                destination.chmod(0o644)
            for skill in skills:
                destination = target / skill
                if os.path.lexists(destination):
                    skipped.append(skill)
                    continue
                try:
                    rename_without_overwrite(staging / skill, destination)
                    installed.append(skill)
                except FileExistsError:
                    skipped.append(skill)
    return {"target": str(target), "installed": installed, "skipped": skipped,
            "sha256": digest, "executedDownloadedCode": False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--base-url", help="Public HTTPS origin (loopback HTTP allowed)")
    source.add_argument("--bundle", help="Local ZIP for offline installation")
    parser.add_argument("--sha256", help="Required expected SHA256 for an offline ZIP")
    parser.add_argument("--target", default="~/.codex/skills", help="Destination (default: ~/.codex/skills)")
    parser.add_argument("--json", action="store_true", help="Print a machine-readable result")
    args = parser.parse_args()
    try:
        result = install(args)
    except (InstallError, OSError, ValueError, zipfile.BadZipFile, HTTPError, URLError) as exc:
        print("Skills installation failed: " + str(exc), file=sys.stderr)
        return 1
    if args.json:
        print(json.dumps(result, ensure_ascii=False))
    else:
        print("安装目录：" + result["target"])
        print("已安装：" + (", ".join(result["installed"]) or "无"))
        print("已存在，跳过且未覆盖：" + (", ".join(result["skipped"]) or "无"))
        print("SHA256 校验通过；未执行下载包中的代码。")
    return 0


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