#!/usr/bin/env python3
"""Kaidera OS release orchestrator.

The command coordinates three deliberately separate products/repos:

* this private engineering superset (dev + commercial builds),
* the AGPL community repository, and
* the public Homebrew/npm metadata repository.

Reversible work is the default. Publishing requires an exact ``--confirm`` value.
Run ``KOS_new_release --help`` or read ``docs/KOS_NEW_RELEASE.md``.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
from datetime import UTC, datetime
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
VERSION_FILE = Path("local-cortex/console/app/version.py")
CHANGELOG_FILE = Path("local-cortex/console/CHANGELOG.md")
MANIFEST_FILE = Path("RELEASE_MANIFEST.json")
PUBLIC_REMOTE = "https://github.com/Kaidera-AI/kaidera-os.git"
PRIVATE_REMOTE = "https://github.com/Kaidera-AI/kaideraos.git"
TAP_REMOTE = "https://github.com/Kaidera-AI/homebrew-kaidera.git"
SEMVER = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
LIVE_ACCEPTANCE_CHECKS = (
    "password_login",
    "grant_pull",
    "capacity_raise",
    "manifold_inference",
    "server_metering",
    "expiry_floor",
    "key_revocation",
    "restore",
    "macos_clean_install",
    "linux_clean_install",
    "upgrade_preserves_state",
    "runtime_reboot_recovery",
)
COMMUNITY_FORBIDDEN_CONTROL_PATHS = (
    "local-cortex/console/app/managed_runtime.py",
    "local-cortex/console/app/native_operator.py",
    "scripts/runtime/apple_container.py",
    "scripts/runtime/apple_container_poc.py",
    "scripts/runtime/migrate-docker-to-apple-container.sh",
    "scripts/runtime/container-engine.sh",
    "scripts/runtime/migrate-docker-to-podman.sh",
)
COMMUNITY_CONTROL_PATTERN = re.compile(
    r"(?:startManagedRuntime|stopManagedRuntime|recoverManagedRuntime|"
    r"/settings/.+?/runtime/(?:start|stop|recover)|managed_runtime_surface)"
)


class ReleaseError(RuntimeError):
    pass


def say(message: str) -> None:
    print(f"\n== {message} ==")


def run(
    command: list[str],
    *,
    cwd: Path = ROOT,
    env: dict[str, str] | None = None,
    capture: bool = False,
) -> subprocess.CompletedProcess[str]:
    print(f"+ ({cwd}) {' '.join(command)}")
    merged_env = os.environ.copy()
    if env:
        merged_env.update(env)
    completed = subprocess.run(
        command,
        cwd=cwd,
        env=merged_env,
        text=True,
        stdout=subprocess.PIPE if capture else None,
        stderr=subprocess.PIPE if capture else None,
        check=False,
    )
    if completed.returncode:
        detail = ""
        if capture:
            detail = f"\n{completed.stdout}{completed.stderr}".rstrip()
        raise ReleaseError(f"command failed ({completed.returncode}): {' '.join(command)}{detail}")
    return completed


def output(command: list[str], *, cwd: Path = ROOT) -> str:
    return run(command, cwd=cwd, capture=True).stdout.strip()


def require_tool(name: str) -> None:
    if shutil.which(name) is None:
        raise ReleaseError(f"required tool is missing: {name}")


def parse_version(value: str) -> tuple[int, int, int]:
    match = SEMVER.fullmatch(value)
    if not match:
        raise ReleaseError(f"invalid version {value!r}; expected X.Y.Z")
    return tuple(int(part) for part in match.groups())  # type: ignore[return-value]


def read_version(repo: Path) -> str:
    text = (repo / VERSION_FILE).read_text(encoding="utf-8")
    match = re.search(r'__version__\s*=\s*"([^"]+)"', text)
    if not match:
        raise ReleaseError(f"cannot read version from {repo / VERSION_FILE}")
    return match.group(1)


def replace_version(repo: Path, old: str, new: str, notes: Path) -> None:
    version_path = repo / VERSION_FILE
    text = version_path.read_text(encoding="utf-8")
    updated, count = re.subn(
        rf'(__version__\s*=\s*"){re.escape(old)}(")',
        rf"\g<1>{new}\2",
        text,
        count=1,
    )
    if count != 1:
        raise ReleaseError(f"failed to bump {version_path}")
    version_path.write_text(updated, encoding="utf-8")

    changelog_path = repo / CHANGELOG_FILE
    changelog = changelog_path.read_text(encoding="utf-8")
    if re.search(rf"^## v{re.escape(new)}(?:\s|$)", changelog, re.MULTILINE):
        raise ReleaseError(f"{changelog_path} already contains v{new}")
    body = notes.read_text(encoding="utf-8").strip()
    if not body:
        raise ReleaseError(f"release notes are empty: {notes}")
    unreleased = re.search(r"^## Unreleased[^\n]*\n", changelog, re.MULTILINE)
    if not unreleased:
        raise ReleaseError(f"cannot find the Unreleased heading in {changelog_path}")
    marker = re.search(r"^## v[0-9]+\.[0-9]+\.[0-9]+", changelog, re.MULTILINE)
    if not marker:
        raise ReleaseError(f"cannot find the first release heading in {changelog_path}")
    if marker.start() < unreleased.end():
        raise ReleaseError(f"invalid CHANGELOG heading order in {changelog_path}")
    date = datetime.now(UTC).date().isoformat()
    entry = f"## v{new} - {date}\n{body}\n\n"
    changelog = (
        changelog[: unreleased.end()]
        + "\n"
        + entry
        + changelog[marker.start() :]
    )
    changelog_path.write_text(changelog, encoding="utf-8")

    run([sys.executable, "scripts/release/gen-release-manifest.py"], cwd=repo)


def git_remote(repo: Path) -> str:
    return output(["git", "remote", "get-url", "origin"], cwd=repo).removesuffix("/")


def normalise_remote(value: str) -> str:
    value = value.removesuffix(".git").removesuffix("/")
    value = re.sub(r"^git@github\.com:", "https://github.com/", value)
    return value


def require_repo(repo: Path | None, expected_remote: str, label: str) -> Path:
    if repo is None:
        raise ReleaseError(f"{label} repo is required; pass --{label}-repo or set its environment variable")
    resolved = repo.expanduser().resolve()
    if not (resolved / ".git").exists():
        raise ReleaseError(f"{label} repo is not a Git checkout: {resolved}")
    actual = normalise_remote(git_remote(resolved))
    expected = normalise_remote(expected_remote)
    if actual != expected:
        raise ReleaseError(f"{label} origin is {actual}, expected {expected}")
    return resolved


def require_clean(repo: Path, label: str) -> None:
    status = output(["git", "status", "--porcelain", "--untracked-files=normal"], cwd=repo)
    if status:
        raise ReleaseError(f"{label} repo is not clean:\n{status}")


def tag_exists(repo: Path, version: str) -> bool:
    return bool(output(["git", "tag", "--list", f"v{version}"], cwd=repo))


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def release_dir(version: str) -> Path:
    path = ROOT / "output" / "release" / f"v{version}"
    path.mkdir(parents=True, exist_ok=True)
    return path


def write_evidence(version: str, phase: str, details: dict[str, Any]) -> Path:
    path = release_dir(version) / f"{phase}.json"
    payload = {
        "schema": "kaidera-os.release-evidence.v1",
        "version": version,
        "phase": phase,
        "recorded_at": datetime.now(UTC).isoformat(),
        **details,
    }
    path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return path


def doctor(args: argparse.Namespace) -> None:
    version = args.version
    parse_version(version)
    public = None
    tap = None
    if not args.commercial_only:
        public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
        tap = require_repo(args.tap_repo, TAP_REMOTE, "tap")

    say("Release channel doctor")
    tools = ["git", "python3", "curl", "tar"]
    if not args.commercial_only:
        tools.extend(("gh", "npm", "ruby"))
    for tool in tools:
        require_tool(tool)
    if os.environ.get("MINISIGN_SECKEY"):
        require_tool("minisign")
    if sys.platform == "darwin":
        for tool in ("security", "pkgbuild", "productbuild", "codesign", "xcrun"):
            require_tool(tool)

    remotes = {"private": normalise_remote(git_remote(ROOT))}
    if public is not None and tap is not None:
        remotes.update(
            {
                "public": normalise_remote(git_remote(public)),
                "tap": normalise_remote(git_remote(tap)),
            }
        )
    if remotes["private"] != normalise_remote(PRIVATE_REMOTE):
        raise ReleaseError(f"private origin is {remotes['private']}, expected {normalise_remote(PRIVATE_REMOTE)}")
    current = {"private": read_version(ROOT)}
    if public is not None:
        current["public"] = read_version(public)
    for label, value in current.items():
        if parse_version(value) > parse_version(version):
            raise ReleaseError(f"{label} source is newer than requested release: {value} > {version}")

    existing_tags = {"private": tag_exists(ROOT, version)}
    if public is not None and tap is not None:
        existing_tags.update(
            {
                "public": tag_exists(public, version),
                "tap": tag_exists(tap, version),
            }
        )
    if any(existing_tags.values()) and not args.resume:
        raise ReleaseError(f"v{version} already exists in at least one local repo; use --resume only for the same release")

    verifier_file = ROOT / "scripts/macos/commercial-license-verifiers.json"
    verifiers = json.loads(verifier_file.read_text(encoding="utf-8"))
    if "kaidera-os-lic-prod-v1" not in verifiers:
        raise ReleaseError("production verifier kaidera-os-lic-prod-v1 is missing")

    evidence = write_evidence(
        version,
        "doctor",
        {
            "remotes": remotes,
            "source_versions": current,
            "existing_local_tags": existing_tags,
            "channel": "commercial-only" if args.commercial_only else "all",
            "production_verifier_kids": sorted(verifiers),
        },
    )
    print(f"doctor passed; evidence: {evidence}")


def prepare(args: argparse.Namespace) -> None:
    public = None
    if not args.commercial_only:
        public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
    if not args.private_notes:
        raise ReleaseError("prepare requires --private-notes")
    if not args.commercial_only and not args.community_notes:
        raise ReleaseError("prepare requires --community-notes")
    new = args.version
    parse_version(new)

    say(f"Prepare source version {new}")
    targets = [(ROOT, args.private_notes, "private")]
    if public is not None and args.community_notes is not None:
        targets.append((public, args.community_notes, "public"))
    for repo, notes, label in targets:
        old = read_version(repo)
        if parse_version(new) <= parse_version(old):
            raise ReleaseError(f"{label} release must increase monotonically: {old} -> {new}")
        replace_version(repo, old, new, notes)
        print(f"prepared {label}: {old} -> {new}")

    details = {
        "private_version": new,
        "channel": "commercial-only" if args.commercial_only else "all",
    }
    if public is not None:
        details["public_version"] = new
    write_evidence(new, "prepare", details)
    target_label = "the private repository" if args.commercial_only else "both repositories"
    print(f"Review and commit {target_label} before verify/build.")


def assert_source_version(version: str, repo: Path, label: str) -> None:
    actual = read_version(repo)
    if actual != version:
        raise ReleaseError(f"{label} source version is {actual}, expected {version}")
    manifest = json.loads((repo / MANIFEST_FILE).read_text(encoding="utf-8"))
    if manifest.get("release_version") != version:
        raise ReleaseError(f"{label} RELEASE_MANIFEST is stale")
    run(
        ["bash", "scripts/fitness/check-version-changelog-sync.sh"],
        cwd=repo,
        env={"KAIDERA_RELEASE_REQUIRE_EMPTY_UNRELEASED": "1"},
    )


def assert_versions(version: str, public: Path | None = None) -> None:
    assert_source_version(version, ROOT, "private")
    if public is not None:
        assert_source_version(version, public, "public")


def validate_live_acceptance(
    path: Path | None,
    version: str,
    *,
    expected_commit: str | None = None,
) -> dict[str, Any]:
    if path is None:
        raise ReleaseError("release-ready verification requires --live-acceptance")
    payload = json.loads(path.read_text(encoding="utf-8"))
    missing = [name for name in LIVE_ACCEPTANCE_CHECKS if payload.get(name) is not True]
    if missing:
        raise ReleaseError(f"live acceptance is incomplete: {', '.join(missing)}")
    if payload.get("environment") != "production":
        raise ReleaseError("live acceptance environment must be production")
    if payload.get("version") not in {version, "source-compatible"}:
        raise ReleaseError("live acceptance version does not match this release")
    commit = str(payload.get("private_commit") or "")
    artifact_sha256 = str(payload.get("artifact_sha256") or "")
    if not re.fullmatch(r"[0-9a-f]{40}", commit):
        raise ReleaseError("live acceptance requires the exact private source commit")
    if expected_commit and commit != expected_commit:
        raise ReleaseError("live acceptance private commit does not match current source")
    if not re.fullmatch(r"[0-9a-f]{64}", artifact_sha256):
        raise ReleaseError("live acceptance requires the installed artifact SHA-256")
    return payload


def validate_build_evidence(
    version: str,
    *,
    expected_commit: str,
    artifact_sha256: str | None = None,
) -> dict[str, Any]:
    path = release_dir(version) / "build.json"
    if not path.is_file():
        raise ReleaseError("release-ready verification requires build.json")
    payload = json.loads(path.read_text(encoding="utf-8"))
    if payload.get("version") != version or payload.get("private_commit") != expected_commit:
        raise ReleaseError("build evidence is not bound to the current private commit")
    artifacts = payload.get("artifacts")
    if not isinstance(artifacts, list) or not artifacts:
        raise ReleaseError("build evidence contains no release artifacts")
    if artifact_sha256 and not any(
        isinstance(item, dict) and item.get("sha256") == artifact_sha256
        for item in artifacts
    ):
        raise ReleaseError("live acceptance artifact is absent from build evidence")
    return payload


def require_release_ready_verification(version: str) -> dict[str, Any]:
    path = ROOT / "output/release" / f"v{version}" / "verify.json"
    if not path.is_file():
        raise ReleaseError("commercial website publication requires verify.json")
    payload = json.loads(path.read_text(encoding="utf-8"))
    live = payload.get("live_acceptance")
    if payload.get("version") != version or payload.get("release_ready") is not True:
        raise ReleaseError("commercial website publication requires release-ready verification")
    if not isinstance(live, dict):
        raise ReleaseError("commercial website publication requires production lifecycle evidence")
    missing = [name for name in LIVE_ACCEPTANCE_CHECKS if live.get(name) is not True]
    if live.get("environment") != "production" or missing:
        raise ReleaseError("commercial website production lifecycle evidence is incomplete")
    current_commit = output(["git", "rev-parse", "HEAD"])
    if payload.get("private_commit") != current_commit:
        raise ReleaseError("release-ready verification is stale for the current source commit")
    if live.get("private_commit") != current_commit:
        raise ReleaseError("production acceptance is not bound to the current source commit")
    artifact_sha256 = str(live.get("artifact_sha256") or "")
    if not re.fullmatch(r"[0-9a-f]{64}", artifact_sha256):
        raise ReleaseError("production acceptance lacks an installed artifact SHA-256")
    validate_build_evidence(
        version,
        expected_commit=current_commit,
        artifact_sha256=artifact_sha256,
    )
    return payload


def validate_tap_package(tap: Path, version: str) -> dict[str, Any]:
    package = json.loads((tap / "npm/package.json").read_text(encoding="utf-8"))
    if package.get("version") != version:
        raise ReleaseError("npm package version is not staged")
    repository = package.get("repository")
    expected = "git+https://github.com/Kaidera-AI/homebrew-kaidera.git"
    if not isinstance(repository, dict) or repository.get("url") != expected:
        raise ReleaseError(
            "npm repository.url must name homebrew-kaidera for trusted-publisher provenance"
        )
    return package


def assert_community_excludes_commercial_controls(public: Path) -> None:
    present = [
        relative
        for relative in COMMUNITY_FORBIDDEN_CONTROL_PATHS
        if (public / relative).exists()
    ]
    if present:
        raise ReleaseError(
            "community source contains commercial Cortex runtime paths: "
            + ", ".join(present)
        )

    hits: list[str] = []
    scan_roots = (
        public / "local-cortex/console/app",
        public / "local-cortex/console/spa/src",
    )
    for root in scan_roots:
        if not root.is_dir():
            continue
        for path in root.rglob("*"):
            if path.suffix not in {".py", ".ts", ".tsx"} or not path.is_file():
                continue
            for number, line in enumerate(
                path.read_text(encoding="utf-8", errors="replace").splitlines(),
                start=1,
            ):
                if COMMUNITY_CONTROL_PATTERN.search(line):
                    hits.append(f"{path.relative_to(public)}:{number}")
    if hits:
        raise ReleaseError(
            "community source contains commercial Cortex control contracts: "
            + ", ".join(hits[:20])
        )


def verify(args: argparse.Namespace) -> None:
    public = None
    tap = None
    if not args.commercial_only:
        public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
        tap = require_repo(args.tap_repo, TAP_REMOTE, "tap")
    version = args.version
    assert_versions(version, public)
    require_clean(ROOT, "private")
    current_commit = output(["git", "rev-parse", "HEAD"])
    qa_env = {"API_PYTHON": sys.executable, "CONSOLE_PYTHON": sys.executable}

    say("Private source and commercial QA")
    if args.quick:
        run([
            "python3",
            "-m",
            "pytest",
            "-q",
            "local-cortex/console/tests/test_license.py",
            "local-cortex/console/tests/test_license_client.py",
            "local-cortex/console/tests/test_kimi_provider.py",
            "local-cortex/console/tests/test_apple_container_poc.py",
        ])
        run(["python3", "-m", "py_compile", "scripts/macos/smoke_commercial_pkg.py"])
        run(["bash", "scripts/fitness/run.sh"])
    else:
        run(["bash", "scripts/qa.sh"], env=qa_env)

    if public is not None and tap is not None:
        say("Community source QA")
        assert_community_excludes_commercial_controls(public)
        run(["bash", "scripts/fitness/check-open-source-runtime-boundary.sh"], cwd=public)
        if args.quick:
            run(["bash", "scripts/fitness/check-oss-package-hygiene.sh"], cwd=public)
            run(["python3", "-m", "compileall", "-q", ".agents/api", ".agents/scripts", "local-cortex/console/app", "redistributable/scripts"], cwd=public)
        else:
            run(["bash", "scripts/qa.sh"], cwd=public, env=qa_env)

        say("Package metadata QA")
        validate_tap_package(tap, version)
        run(["bash", "-n", "install.sh"], cwd=tap)
        run(["ruby", "-c", "Formula/kaidera-os.rb"], cwd=tap)
        run(["node", "--check", "npm/bin/cli.js"], cwd=tap)
        run(["python3", "-m", "unittest", "discover", "-s", "tests"], cwd=tap)

    live: dict[str, Any] | None = None
    if args.release_ready:
        live = validate_live_acceptance(
            args.live_acceptance,
            version,
            expected_commit=current_commit,
        )
        validate_build_evidence(
            version,
            expected_commit=current_commit,
            artifact_sha256=str(live["artifact_sha256"]),
        )
    details = {
        "quick": bool(args.quick),
        "release_ready": bool(args.release_ready),
        "live_acceptance": live,
        "channel": "commercial-only" if args.commercial_only else "all",
        "private_commit": current_commit,
    }
    if public is not None and tap is not None:
        details["public_commit"] = output(["git", "rev-parse", "HEAD"], cwd=public)
        details["tap_commit"] = output(["git", "rev-parse", "HEAD"], cwd=tap)
    evidence = write_evidence(version, "verify", details)
    print(f"verification passed; evidence: {evidence}")


def build(args: argparse.Namespace) -> None:
    public = None
    if not args.commercial_only:
        public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
    version = args.version
    assert_versions(version, public)
    require_clean(ROOT, "private")
    if public is not None:
        require_clean(public, "public")

        say("Build community archive")
        run(["bash", "scripts/release/build-community-release.sh", version], cwd=public)

    say("Build commercial server archive")
    verifier_map = (ROOT / "scripts/macos/commercial-license-verifiers.json").read_text(encoding="utf-8").strip()
    run(["bash", "dist/release.sh", version], env={"KAIDERA_OS_LICENSE_VERIFY_KEYS": verifier_map})

    say("Build signed and notarized commercial macOS package")
    required_env = (
        "KAIDERA_OS_CODESIGN_IDENTITY",
        "KAIDERA_OS_INSTALLER_IDENTITY",
        "KAIDERA_OS_NOTARY_PROFILE",
    )
    missing = [name for name in required_env if not os.environ.get(name)]
    if missing:
        raise ReleaseError(f"commercial PKG build requires: {', '.join(missing)}")
    release_env = {
        "KAIDERA_OS_PLATFORM_URL": "https://api.kaidera.ai",
        "KAIDERA_OS_PORTAL_URL": "https://app.kaidera.ai",
        "KAIDERA_MANIFOLD_BASE_URL": "https://api.kaidera.ai/v1",
        "KAIDERA_OS_PRODUCTION_LICENSE_KID": "kaidera-os-lic-prod-v1",
        "KAIDERA_OS_REQUIRE_RELEASE_SIGNING": "1",
    }
    run(["bash", "scripts/macos/build-commercial-pkg.sh"], env=release_env)
    package = ROOT / "dist/macos" / f"kaidera-os-commercial-v{version}-macos-arm64.pkg"
    run(
        [
            "python3",
            "scripts/macos/smoke_commercial_pkg.py",
            str(package),
            "--no-launch",
        ]
    )

    commercial_server = ROOT / "output/release/kaidera-os-commercial-server"
    commercial_macos = ROOT / "output/release/kaidera-os-commercial-macos-installer"
    artifact_roots = [commercial_server, commercial_macos]
    if public is not None:
        artifact_roots.insert(0, public / "output/release/community")
    artifacts = sorted(
        path
        for base in artifact_roots
        for path in base.glob("*")
        if path.is_file()
    )
    evidence = write_evidence(
        version,
        "build",
        {
            "channel": "commercial-only" if args.commercial_only else "all",
            "private_commit": output(["git", "rev-parse", "HEAD"]),
            "artifacts": [
                {"path": str(path), "size": path.stat().st_size, "sha256": sha256(path)}
                for path in artifacts
            ]
        },
    )
    print(f"build passed; evidence: {evidence}")


def publish_community(args: argparse.Namespace) -> None:
    public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
    version = args.version
    expected = f"publish-v{version}"
    if args.confirm != expected:
        raise ReleaseError(f"refusing to publish; pass --confirm {expected}")
    require_clean(public, "public")
    if read_version(public) != version:
        raise ReleaseError("public version does not match")

    bundle = public / "output/release/community"
    archive = bundle / f"kaidera-os-v{version}.tar.gz"
    checksum = archive.with_suffix(archive.suffix + ".sha256")
    signature = archive.with_suffix(archive.suffix + ".minisig")
    for path in (archive, checksum):
        if not path.is_file():
            raise ReleaseError(f"community artifact missing: {path}")
    assets = [str(archive), str(checksum)]
    if signature.is_file():
        assets.append(str(signature))
    run(["git", "push", "origin", "HEAD:main"], cwd=public)
    if not tag_exists(public, version):
        run(["git", "tag", "-a", f"v{version}", "-m", f"Kaidera OS v{version}"], cwd=public)
    run(["git", "push", "origin", f"v{version}"], cwd=public)
    run(
        [
            "gh", "release", "create", f"v{version}",
            *assets,
            "--repo", "Kaidera-AI/kaidera-os",
            "--verify-tag",
            "--title", f"Kaidera OS v{version}",
            "--generate-notes",
        ],
        cwd=public,
    )
    write_evidence(version, "publish-community", {"tag": f"v{version}", "sha256": sha256(archive)})


def stage_tap(args: argparse.Namespace) -> None:
    public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
    tap = require_repo(args.tap_repo, TAP_REMOTE, "tap")
    version = args.version
    archive = public / "output/release/community" / f"kaidera-os-v{version}.tar.gz"
    if not archive.is_file():
        raise ReleaseError(f"build the community archive first: {archive}")
    digest = sha256(archive)
    url = f"https://github.com/Kaidera-AI/kaidera-os/releases/download/v{version}/kaidera-os-v{version}.tar.gz"

    replacements = {
        tap / "Formula/kaidera-os.rb": [
            (r'^  url ".*"$', f'  url "{url}"'),
            (r'^  sha256 ".*"$', f'  sha256 "{digest}"'),
            (r'assert_match "[0-9]+\.[0-9]+\.[0-9]+"', f'assert_match "{version}"'),
            (r"Manifold-only edition", "provider-free edition"),
        ],
        tap / "install.sh": [
            (r'^VERSION="\$\{KAIDERA_OS_VERSION:-[0-9]+\.[0-9]+\.[0-9]+\}"$', f'VERSION="${{KAIDERA_OS_VERSION:-{version}}}"'),
        ],
        tap / "npm/package.json": [
            (r'"version": "[0-9]+\.[0-9]+\.[0-9]+"', f'"version": "{version}"'),
        ],
    }
    for path, rules in replacements.items():
        text = path.read_text(encoding="utf-8")
        for pattern, replacement in rules:
            updated, count = re.subn(pattern, replacement, text, count=1, flags=re.MULTILINE)
            if count == 0 and replacement in text:
                continue
            if count != 1:
                raise ReleaseError(f"tap metadata pattern not found in {path}: {pattern}")
            text = updated
        path.write_text(text, encoding="utf-8")

    cli_path = tap / "npm/bin/cli.js"
    cli = cli_path.read_text(encoding="utf-8")
    cli = re.sub(
        r"const RELEASE_REPO =\n  VERSION === '0\.1\.231' \? 'Kaidera-AI/homebrew-kaidera' : 'Kaidera-AI/kaidera-os'",
        "const RELEASE_REPO = 'Kaidera-AI/kaidera-os'",
        cli,
        count=1,
    )
    cli_path.write_text(cli, encoding="utf-8")

    installer = tap / "install.sh"
    installer_text = installer.read_text(encoding="utf-8")
    installer_text = re.sub(
        r'if \[ "\$VERSION" = "0\.1\.231" \]; then\n  RELEASE_REPO="Kaidera-AI/homebrew-kaidera"\nelse\n  RELEASE_REPO="Kaidera-AI/kaidera-os"\nfi',
        'RELEASE_REPO="Kaidera-AI/kaidera-os"',
        installer_text,
        count=1,
    )
    installer.write_text(installer_text, encoding="utf-8")
    write_evidence(version, "stage-tap", {"url": url, "sha256": digest})
    print(f"staged Homebrew/npm metadata for v{version}; review and commit {tap}")


def publish_packages(args: argparse.Namespace) -> None:
    tap = require_repo(args.tap_repo, TAP_REMOTE, "tap")
    version = args.version
    expected = f"publish-packages-v{version}"
    if args.confirm != expected:
        raise ReleaseError(f"refusing to publish packages; pass --confirm {expected}")
    require_clean(tap, "tap")
    validate_tap_package(tap, version)
    run(["gh", "release", "view", f"v{version}", "--repo", "Kaidera-AI/kaidera-os"])
    run(["git", "push", "origin", "HEAD:main"], cwd=tap)
    if not tag_exists(tap, version):
        run(["git", "tag", "-a", f"v{version}", "-m", f"Kaidera OS package channels v{version}"], cwd=tap)
    run(["git", "push", "origin", f"v{version}"], cwd=tap)
    run(
        [
            "gh", "release", "create", f"v{version}",
            "--repo", "Kaidera-AI/homebrew-kaidera",
            "--verify-tag",
            "--title", f"Kaidera OS package channels v{version}",
            "--notes", "Publishes the matching Homebrew and npm launchers. Runtime assets are hosted by the Kaidera OS community release.",
        ],
        cwd=tap,
    )
    write_evidence(version, "publish-packages", {"trusted_publisher_workflow": "publish-npm.yml"})


def website_packet(args: argparse.Namespace) -> None:
    version = args.version
    verification = require_release_ready_verification(version)
    source = ROOT / "output/release/kaidera-os-commercial-macos-installer"
    metadata_path = source / f"kaidera-os-commercial-v{version}-macos-arm64.pkg.metadata.json"
    package_path = source / f"kaidera-os-commercial-v{version}-macos-arm64.pkg"
    if not metadata_path.is_file() or not package_path.is_file():
        raise ReleaseError("commercial website artifacts have not been built")
    metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
    if metadata.get("commercial_release_ready") is not True:
        raise ReleaseError("commercial package metadata is not release-ready")
    if metadata.get("commit") != verification.get("private_commit"):
        raise ReleaseError("commercial package commit does not match release verification")
    if metadata.get("sha256") != sha256(package_path):
        raise ReleaseError("commercial package checksum does not match metadata")
    if metadata.get("sha256") != verification["live_acceptance"].get("artifact_sha256"):
        raise ReleaseError("commercial package was not the production-accepted artifact")

    destination = release_dir(version) / "website"
    destination.mkdir(parents=True, exist_ok=True)
    for path in source.iterdir():
        if path.is_file():
            shutil.copy2(path, destination / path.name)
    handoff = destination / f"scribe-website-update-v{version}.md"
    handoff.write_text(
        f"# Kaidera OS v{version} website release\n\n"
        "Target: `scribe@kaidera`\n\n"
        "Update `https://kaidera.ai/downloads/kaidera-os/macos#install` with the "
        f"signed commercial installer `{package_path.name}`. Host the commercial bytes only "
        "on `kaidera.ai`; do not attach them to a GitHub release.\n\n"
        f"- Version: `{version}`\n"
        f"- SHA-256: `{metadata['sha256']}`\n"
        f"- Size: `{metadata.get('size_bytes', package_path.stat().st_size)}` bytes\n"
        f"- Source commit: `{metadata.get('commit', '')}`\n"
        f"- Release ready: `{str(metadata['commercial_release_ready']).lower()}`\n"
        "- Installation: one Apple-silicon PKG; macOS 26+; Operator installs/repairs the runtime and prerequisites.\n"
        "- Licensing: nine-day trial, then Kaidera Platform activation; BYOK remains hidden until granted.\n"
        "- Keep the shared component name Cortex unchanged.\n\n"
        "After publishing, return the final anonymous HTTPS asset URL and page URL so the release owner can verify both before Homebrew commercial promotion.\n",
        encoding="utf-8",
    )
    write_evidence(version, "website-packet", {"directory": str(destination), "handoff": str(handoff)})
    print(f"website packet ready: {handoff}")


def status(args: argparse.Namespace) -> None:
    version = args.version
    say(f"Release v{version} status")
    print(f"private source: {read_version(ROOT)} @ {output(['git', 'rev-parse', '--short', 'HEAD'])}")
    if args.public_repo:
        public = require_repo(args.public_repo, PUBLIC_REMOTE, "public")
        print(f"public source:  {read_version(public)} @ {output(['git', 'rev-parse', '--short', 'HEAD'], cwd=public)}")
    if args.tap_repo:
        tap = require_repo(args.tap_repo, TAP_REMOTE, "tap")
        package = json.loads((tap / "npm/package.json").read_text(encoding="utf-8"))
        print(f"npm metadata:  {package.get('version')} @ {output(['git', 'rev-parse', '--short', 'HEAD'], cwd=tap)}")
    evidence = release_dir(version)
    for path in sorted(evidence.glob("*.json")):
        print(f"evidence:      {path.name}")


def parser() -> argparse.ArgumentParser:
    result = argparse.ArgumentParser(description=__doc__)
    result.add_argument(
        "phase",
        choices=(
            "status", "doctor", "prepare", "verify", "build",
            "stage-tap", "publish-community", "publish-packages", "website-packet",
        ),
    )
    result.add_argument("version", help="immutable release version, without the v prefix")
    result.add_argument("--public-repo", type=Path, default=os.environ.get("KAIDERA_OS_PUBLIC_REPO"))
    result.add_argument("--tap-repo", type=Path, default=os.environ.get("KAIDERA_OS_TAP_REPO"))
    result.add_argument("--private-notes", type=Path)
    result.add_argument("--community-notes", type=Path)
    result.add_argument("--live-acceptance", type=Path)
    result.add_argument("--release-ready", action="store_true", help="require complete production lifecycle evidence")
    result.add_argument(
        "--commercial-only",
        action="store_true",
        help="operate only on private commercial source; leave community and package channels unchanged",
    )
    result.add_argument("--quick", action="store_true", help="run focused checks; never sufficient for publication")
    result.add_argument("--resume", action="store_true", help="allow an existing local release tag")
    result.add_argument("--confirm", default="", help="exact confirmation required by publish phases")
    return result


def main(argv: list[str] | None = None) -> int:
    args = parser().parse_args(argv)
    args.public_repo = Path(args.public_repo) if args.public_repo else None
    args.tap_repo = Path(args.tap_repo) if args.tap_repo else None
    actions = {
        "status": status,
        "doctor": doctor,
        "prepare": prepare,
        "verify": verify,
        "build": build,
        "stage-tap": stage_tap,
        "publish-community": publish_community,
        "publish-packages": publish_packages,
        "website-packet": website_packet,
    }
    try:
        if args.commercial_only and args.phase in {
            "stage-tap",
            "publish-community",
            "publish-packages",
        }:
            raise ReleaseError(f"{args.phase} is not available with --commercial-only")
        actions[args.phase](args)
    except (ReleaseError, OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"KOS_new_release: {exc}", file=sys.stderr)
        return 1
    return 0


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