#!/usr/bin/env python3
"""Zero-dependency CLI client for Integrity Harness Cloud Control Plane.

Stdlib-only (Python 3.10+). Uploads only SHA-256 digests and compact metadata
(never source code or credentials).
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any

DEFAULT_BASE_URL = "https://integrity.subnet.zp.ua"
USER_AGENT = "integrity-harness-cli/1.0"
MAX_PAYLOAD_BYTES = 16 * 1024
_UNSAFE_ID_CHARS = re.compile(r"[^A-Za-z0-9._:-]+")


def sanitize_id(raw: str | None, fallback: str) -> str:
    cleaned = _UNSAFE_ID_CHARS.sub("-", (raw or "").strip()).strip("-")[:64]
    return cleaned or fallback


def default_host_id() -> str:
    raw = (
        os.environ.get("INTEGRITY_HOST_ID")
        or os.environ.get("COMPUTERNAME")
        or os.environ.get("HOSTNAME")
        or "default-host"
    )
    return sanitize_id(raw, "default-host")


def default_turn_id() -> str:
    return f"turn-{int(time.time())}-{secrets.token_hex(4)}"


def sha256_file(path: Path) -> str:
    hasher = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(65536), b""):
            hasher.update(chunk)
    return hasher.hexdigest()


def api_request(
    base_url: str,
    path: str,
    method: str = "GET",
    payload: dict[str, Any] | None = None,
    license_key: str | None = None,
    owner_admin_token: str | None = None,
    timeout: int = 15,
) -> tuple[int, dict[str, Any]]:
    url = base_url.rstrip("/") + path
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/json",
    }
    if license_key and license_key.strip():
        headers["Authorization"] = f"Bearer {license_key.strip()}"
    if owner_admin_token and owner_admin_token.strip():
        headers["x-owner-admin-token"] = owner_admin_token.strip()
    data: bytes | None = None
    if payload is not None:
        data = json.dumps(payload, separators=(",", ":")).encode("utf-8")
        if len(data) > MAX_PAYLOAD_BYTES:
            raise ValueError(f"payload exceeds {MAX_PAYLOAD_BYTES} byte metadata limit")
        headers["Content-Type"] = "application/json"

    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8", "replace")
            return resp.status, json.loads(raw) if raw.strip() else {}
    except urllib.error.HTTPError as exc:
        raw = exc.read().decode("utf-8", "replace")
        try:
            body = json.loads(raw)
        except ValueError:
            body = {"ok": False, "error": raw or str(exc)}
        return exc.code, body


def build_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(
        prog="integrity-cloud",
        description="Integrity Harness Cloud Control Plane CLI (Cloud Witness & Central Killswitch)",
    )
    ap.add_argument("--base-url", default=os.environ.get("INTEGRITY_BASE_URL", DEFAULT_BASE_URL))
    ap.add_argument(
        "--license-key",
        default=os.environ.get("INTEGRITY_LICENSE_KEY", ""),
        help="Tenant Bearer license key (IH-...) or env INTEGRITY_LICENSE_KEY",
    )
    ap.add_argument(
        "--admin-token",
        default=os.environ.get("INTEGRITY_OWNER_ADMIN_TOKEN", ""),
        help="Owner admin token for restore actions (or env INTEGRITY_OWNER_ADMIN_TOKEN)",
    )
    sub = ap.add_subparsers(dest="cmd", required=True)

    sub.add_parser("health", help="Check Cloud Control Plane health and active bindings")

    lc = sub.add_parser("license-claim", help="Claim your active IH-... license key using Creem Order ID and email")
    lc.add_argument("--order-id", required=True, help="Creem Order ID from your payment receipt")
    lc.add_argument("--email", required=True, help="Email address used during Creem checkout")

    wn = sub.add_parser("witness-notarize", help="Notarize a SHA-256 event digest in Cloud Witness")
    wn.add_argument(
        "--host-id",
        "--host",
        dest="host_id",
        default=None,
        help="Host identifier (defaults to INTEGRITY_HOST_ID / hostname)",
    )
    wn.add_argument(
        "--agent-id",
        default=os.environ.get("INTEGRITY_AGENT_ID", "cli-agent"),
        help="Agent identifier (e.g. claude-code, codex-cli, cli-agent)",
    )
    wn.add_argument(
        "--turn-id",
        default=None,
        help="Turn or event identifier (auto-generated if omitted)",
    )
    wn.add_argument("--sha256", "--event-sha256", dest="digest_hex", help="64-hex SHA-256 digest to pin")
    wn.add_argument("--file", dest="artifact_file", help="Compute SHA-256 locally from file (file is never uploaded)")
    wn.add_argument("--coverage-debt", type=int, default=0, help="Unnotarized coverage debt count (default: 0)")
    wn.add_argument("--tool-count", type=int, default=0, help="Tool invocations in this turn (default: 0)")
    wn.add_argument("--tokens-total", type=int, default=0, help="Total tokens consumed in this turn (default: 0)")

    wl = sub.add_parser("witness-list", help="Read latest Cloud Witness chain head for a host")
    wl.add_argument(
        "--host-id",
        "--host",
        dest="host_id",
        default=None,
        help="Host identifier (defaults to INTEGRITY_HOST_ID / hostname)",
    )

    sub.add_parser("killswitch-get", help="Read current Central Killswitch state")

    kp = sub.add_parser("killswitch-panic", help="Trigger Master Panic across your fleet (tighten-only)")
    kp.add_argument("--reason", default="Fleet panic triggered")
    kp.add_argument("--actor", default="cli-agent")

    ko = sub.add_parser("killswitch-off", help="Disable a specific agent vendor across your fleet (tighten-only)")
    ko.add_argument("--target", required=True, help="Vendor name (e.g. claude, codex, cursor)")
    ko.add_argument("--reason", default="")
    ko.add_argument("--actor", default="cli-agent")

    kso = sub.add_parser(
        "killswitch-scope-off",
        help="Disable a specific action scope across your fleet (tighten-only)",
    )
    kso.add_argument("--target", required=True, help="Action scope (e.g. deploy, ssh, secrets)")
    kso.add_argument("--reason", default="")
    kso.add_argument("--actor", default="cli-agent")

    kr = sub.add_parser("killswitch-resume", help="Clear Master Panic (requires owner --admin-token)")
    kr.add_argument("--reason", default="owner-verified-resume")
    kr.add_argument("--actor", default="owner-cli")

    kon = sub.add_parser("killswitch-on", help="Re-enable a disabled vendor (requires owner --admin-token)")
    kon.add_argument("--target", required=True, help="Vendor name (e.g. claude, codex, cursor)")
    kon.add_argument("--reason", default="owner-verified-on")
    kon.add_argument("--actor", default="owner-cli")

    kson = sub.add_parser("killswitch-scope-on", help="Re-enable a disabled scope (requires owner --admin-token)")
    kson.add_argument("--target", required=True, help="Action scope (e.g. deploy, ssh, secrets)")
    kson.add_argument("--reason", default="owner-verified-scope-on")
    kson.add_argument("--actor", default="owner-cli")

    return ap


def main(argv: list[str] | None = None) -> int:
    ap = build_parser()
    args = ap.parse_args(argv)

    if args.cmd == "health":
        status, body = api_request(args.base_url, "/api/v1/health")
        print(json.dumps(body, indent=2))
        return 0 if status == 200 and body.get("ok") else 2

    if args.cmd == "license-claim":
        payload = {
            "order_id": args.order_id.strip(),
            "email": args.email.strip().lower(),
        }
        status, body = api_request(args.base_url, "/api/v1/license/claim", method="POST", payload=payload)
        print(json.dumps(body, indent=2))
        return 0 if status == 200 and body.get("ok") else 3

    license_key = (args.license_key or "").strip()
    if not license_key:
        print(json.dumps({"ok": False, "error": "Missing --license-key or INTEGRITY_LICENSE_KEY env var"}))
        return 2

    if args.cmd == "witness-notarize":
        digest = (args.digest_hex or "").strip()
        if not digest and args.artifact_file:
            artifact_path = Path(args.artifact_file)
            if not artifact_path.is_file():
                print(json.dumps({"ok": False, "error": f"File not found: {artifact_path}"}))
                return 2
            digest = sha256_file(artifact_path)
        if not digest:
            print(json.dumps({"ok": False, "error": "Provide --sha256 or --file"}))
            return 2

        host_id = sanitize_id(args.host_id, default_host_id())
        agent_id = sanitize_id(args.agent_id, "cli-agent")
        turn_id = sanitize_id(args.turn_id, default_turn_id())
        payload: dict[str, Any] = {
            "host_id": host_id,
            "agent_id": agent_id,
            "turn_id": turn_id,
            "event_sha256": digest.lower(),
            "coverage_debt": max(0, int(args.coverage_debt)),
            "tool_count": max(0, int(args.tool_count)),
            "tokens_total": max(0, int(args.tokens_total)),
        }
        status, body = api_request(
            args.base_url, "/api/v1/witness/notarize", method="POST", payload=payload, license_key=license_key
        )
        print(json.dumps(body, indent=2))
        return 0 if status in (200, 201) else 3

    if args.cmd == "witness-list":
        host_id = sanitize_id(args.host_id, default_host_id())
        query = urllib.parse.urlencode({"host_id": host_id})
        status, body = api_request(
            args.base_url, f"/api/v1/witness/notarize?{query}", license_key=license_key
        )
        print(json.dumps(body, indent=2))
        return 0 if status == 200 else 3

    if args.cmd == "killswitch-get":
        status, body = api_request(args.base_url, "/api/v1/killswitch/state", license_key=license_key)
        print(json.dumps(body, indent=2))
        return 0 if status == 200 else 3

    if args.cmd in ("killswitch-panic", "killswitch-off", "killswitch-scope-off"):
        action_map = {
            "killswitch-panic": "panic",
            "killswitch-off": "off",
            "killswitch-scope-off": "scope-off",
        }
        payload = {
            "action": action_map[args.cmd],
            "reason": args.reason,
            "actor": args.actor,
        }
        if args.cmd != "killswitch-panic":
            payload["target"] = args.target.strip().lower()
        status, body = api_request(
            args.base_url, "/api/v1/killswitch/state", method="POST", payload=payload, license_key=license_key
        )
        print(json.dumps(body, indent=2))
        return 0 if status == 200 else 3

    # Owner-only restore commands: killswitch-resume, killswitch-on, killswitch-scope-on
    admin_token = (args.admin_token or "").strip()
    if not admin_token:
        err = f"{args.cmd} requires --admin-token or INTEGRITY_OWNER_ADMIN_TOKEN"
        print(json.dumps({"ok": False, "error": err}))
        return 2

    restore_map = {
        "killswitch-resume": "resume",
        "killswitch-on": "on",
        "killswitch-scope-on": "scope-on",
    }
    payload = {
        "action": restore_map[args.cmd],
        "reason": args.reason,
        "actor": args.actor,
    }
    if args.cmd != "killswitch-resume":
        payload["target"] = args.target.strip().lower()

    status, body = api_request(
        args.base_url,
        "/api/v1/killswitch/state",
        method="POST",
        payload=payload,
        license_key=license_key,
        owner_admin_token=admin_token,
    )
    print(json.dumps(body, indent=2))
    return 0 if status == 200 else 3


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