#!/usr/bin/env python3
"""Verify, stage, and install the CRUX Decision plugin with the native CLI."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import secrets
import shutil
import stat
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
from typing import Optional


RELEASE_URL = "https://crux.sunya.ai/downloads/crux-decision-0.7.0.zip"
RELEASE_SHA256 = "09d47f91cd652f0512497f09985c4b28baf377a404c803a033aced8fc23f456c"
RELEASE_VERSION = "0.7.0"
MARKETPLACE = "crux-decision-astra"
PLUGIN = "crux-decision"
MIN_PYTHON = (3, 9)


class InstallError(RuntimeError):
    """An actionable failure while preparing or installing CRUX."""


def _run(command: list[str]) -> subprocess.CompletedProcess:
    try:
        result = subprocess.run(command, text=True, capture_output=True, check=False)
    except OSError as exc:
        raise InstallError(f"Could not run {command[0]}: {exc}") from exc
    if result.returncode:
        detail = (result.stderr or result.stdout).strip()
        raise InstallError(
            f"Command failed ({result.returncode}): {' '.join(command)}"
            + (f"\n{detail}" if detail else "")
        )
    return result


def _download(url: str) -> bytes:
    try:
        with urllib.request.urlopen(url, timeout=30) as response:
            return response.read()
    except Exception as exc:
        raise InstallError(f"Could not download the CRUX release from {url}: {exc}") from exc


def _verified_bytes(archive: Optional[Path], url: str, expected_sha256: str) -> bytes:
    if archive is None:
        data = _download(url)
    else:
        try:
            data = archive.expanduser().read_bytes()
        except OSError as exc:
            raise InstallError(f"Could not read ZIP archive {archive}: {exc}") from exc
    actual = hashlib.sha256(data).hexdigest()
    if actual.lower() != expected_sha256.lower():
        raise InstallError(
            "CRUX ZIP checksum did not match the pinned release. "
            f"Expected {expected_sha256}; received {actual}. No files were staged."
        )
    return data


def _safe_extract(data: bytes, destination: Path) -> Path:
    """Extract a verified ZIP only after rejecting unsafe or ambiguous entries."""
    try:
        import io

        with zipfile.ZipFile(io.BytesIO(data)) as bundle:
            seen: set[str] = set()
            for info in bundle.infolist():
                name = info.filename
                path = PurePosixPath(name)
                raw_parts = name.rstrip("/").split("/")
                mode = info.external_attr >> 16
                if (
                    not name
                    or "\x00" in name
                    or "\\" in name
                    or not path.parts
                    or ":" in path.parts[0]
                    or path.is_absolute()
                    or any(part in ("", ".", "..") for part in path.parts)
                    or any(part in ("", ".", "..") for part in raw_parts)
                    or path.as_posix() in seen
                    or stat.S_ISLNK(mode)
                ):
                    raise InstallError(f"Unsafe or duplicate ZIP entry: {name!r}")
                seen.add(path.as_posix())
            bundle.extractall(destination)
    except InstallError:
        raise
    except (zipfile.BadZipFile, OSError, RuntimeError, NotImplementedError) as exc:
        raise InstallError(f"Could not safely unpack the CRUX ZIP archive: {exc}") from exc

    package = destination / PLUGIN
    if not package.is_dir() or not (package / "VALIDATE.py").is_file():
        raise InstallError("The verified ZIP does not contain crux-decision/VALIDATE.py.")
    return package


def _validate(package: Path) -> None:
    result = _run([sys.executable, str(package / "VALIDATE.py")])
    output = (result.stdout + "\n" + result.stderr).strip()
    if '"status": "PASS"' not in output and '"status":"PASS"' not in output:
        raise InstallError(
            "The bundled CRUX package validator did not report PASS. "
            + (output or "Inspect the extracted package and retry.")
        )


def _stage_name(destination: Path) -> Path:
    for _ in range(10):
        candidate = destination / f"crux-decision-0.7.0-{secrets.token_hex(4)}"
        if not candidate.exists():
            return candidate
    raise InstallError(f"Could not choose a new staging folder inside {destination}.")


def _native_install(host: str, cli: str, stage: Path) -> None:
    if host == "codex":
        marketplace = _run([cli, "plugin", "marketplace", "add", str(stage), "--json"])
        try:
            receipt = json.loads(marketplace.stdout)
            installed_root = Path(receipt["installedRoot"]).expanduser().resolve()
        except (json.JSONDecodeError, KeyError, TypeError, OSError, ValueError) as exc:
            raise InstallError(
                "Codex did not return a marketplace source receipt. The new source is staged at "
                f"{stage}; inspect Codex's marketplace registration before retrying."
            ) from exc
        if installed_root != stage.resolve():
            raise InstallError(
                "Codex already resolves this marketplace name to a different source: "
                f"{installed_root} (expected {stage}). No plugin was added. The new package "
                f"remains staged at {stage}; inspect the existing marketplace registration "
                "and resolve it manually before retrying."
            )
        plugin = _run([cli, "plugin", "add", f"{PLUGIN}@{MARKETPLACE}", "--json"])
        try:
            plugin_receipt = json.loads(plugin.stdout)
        except json.JSONDecodeError as exc:
            raise InstallError(
                "Codex did not return a plugin-install receipt. Check Codex's plugin state "
                f"before retrying; package source remains at {stage}."
            ) from exc
        if (
            plugin_receipt.get("pluginId") != f"{PLUGIN}@{MARKETPLACE}"
            or plugin_receipt.get("version") != RELEASE_VERSION
        ):
            raise InstallError(
                "Codex's plugin-install receipt did not match CRUX Decision 0.7.0. "
                f"Check Codex's plugin state; package source remains at {stage}."
            )
        return

    parent_help = _run([cli, "plugin", "--help"])
    parent_text = (parent_help.stdout + "\n" + parent_help.stderr).lower()
    if "marketplace" not in parent_text or "install" not in parent_text:
        raise InstallError(
            "This Claude CLI does not document plugin marketplace and install commands. "
            "Update Claude Code or use its supported plugin UI."
        )
    marketplace_help = _run([cli, "plugin", "marketplace", "add", "--help"])
    install_help = _run([cli, "plugin", "install", "--help"])
    marketplace_text = (marketplace_help.stdout + "\n" + marketplace_help.stderr).lower()
    install_text = (install_help.stdout + "\n" + install_help.stderr).lower()
    if "marketplace" not in marketplace_text or "add" not in marketplace_text:
        raise InstallError(
            "This Claude CLI does not document `plugin marketplace add`. "
            "Update Claude Code or use its supported plugin UI."
        )
    if "--scope" not in install_text or "user" not in install_text:
        raise InstallError(
            "This Claude CLI does not document `plugin install --scope user`. "
            "Update Claude Code or use its supported plugin UI."
        )
    _run([cli, "plugin", "marketplace", "add", str(stage)])
    _run([cli, "plugin", "install", f"{PLUGIN}@{MARKETPLACE}", "--scope", "user"])


def install(
    host: str,
    destination: Path,
    archive: Optional[Path] = None,
    *,
    cli_path: Optional[str] = None,
    url: str = RELEASE_URL,
    expected_sha256: str = RELEASE_SHA256,
) -> Path:
    if sys.version_info < MIN_PYTHON:
        raise InstallError("Python 3.9 or newer is required. Install a current Python 3 and retry.")
    if host not in ("codex", "claude"):
        raise InstallError("Choose --host codex or --host claude.")

    executable = cli_path or shutil.which(host)
    if not executable:
        product = "Codex CLI" if host == "codex" else "Claude Code CLI"
        raise InstallError(f"{product} was not found on PATH. Install it, sign in, then retry.")

    data = _verified_bytes(archive, url, expected_sha256)
    try:
        destination = destination.expanduser().resolve()
    except OSError as exc:
        raise InstallError(f"Could not resolve destination folder {destination}: {exc}") from exc
    if destination.exists() and not destination.is_dir():
        raise InstallError(f"Destination must be a folder: {destination}")

    # Extraction is temporary; the staged copy below is the durable source used by
    # the host. Nothing is written to the user's chosen destination before checksum
    # and archive-path checks have passed.
    with tempfile.TemporaryDirectory(prefix="crux-install-") as temporary:
        package = _safe_extract(data, Path(temporary))
        _validate(package)
        try:
            destination.mkdir(parents=True, exist_ok=True)
        except OSError as exc:
            raise InstallError(f"Could not prepare destination folder {destination}: {exc}") from exc
        stage = _stage_name(destination)
        _run([sys.executable, str(package / "scripts" / "stage_marketplace.py"), str(stage)])
        staged_package = stage / "plugins" / PLUGIN
        _validate(staged_package)

    _native_install(host, executable, stage)
    return stage


def main(argv: Optional[list[str]] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", choices=("codex", "claude"), required=True)
    parser.add_argument(
        "--destination",
        type=Path,
        default=Path.home() / ".local" / "share" / "crux",
        help="Parent folder for a new durable staging copy (default: ~/.local/share/crux)",
    )
    parser.add_argument("--archive", type=Path, help="Use a local ZIP instead of downloading the pinned release")
    args = parser.parse_args(argv)
    try:
        stage = install(args.host, args.destination, args.archive)
    except InstallError as exc:
        print(f"CRUX setup failed: {exc}", file=sys.stderr)
        return 1
    except (OSError, ValueError) as exc:
        print(f"CRUX setup failed because of a local path or file error: {exc}", file=sys.stderr)
        return 1

    print(f"CRUX Decision {RELEASE_VERSION} was staged at: {stage}")
    print("The native plugin install command completed.")
    print("Restart your host, open a fresh task, and confirm all five CRUX Decision skills appear.")
    print("Then ask one first-look question. Install completion does not prove skill discovery or invocation.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
