"""Create a self-contained air-gapped install bundle.

Produces a tar.gz archive containing:
- The installed vault files
- A pip requirements snapshot (pip freeze)
- An offline-install.sh script

See docs/ENTERPRISE_INSTALL.md for usage.
"""

from __future__ import annotations

import json
import os
import subprocess
import sys
import tarfile
import tempfile
from pathlib import Path


def _get_vault_dir() -> Path:
    """Return the currently installed vault directory."""
    plugin_dir = Path(os.environ.get("CLAUDE_PLUGIN_DIR", Path.home() / ".claude" / "tribunal"))
    return plugin_dir


def create_bundle(output: str = "tribunal-bundle.tar.gz", vault_dir: str | None = None) -> None:
    """Create an air-gapped install bundle at *output*.

    Parameters
    ----------
    output:
        Path for the output .tar.gz file.
    vault_dir:
        Override the vault directory to bundle. Defaults to the installed vault.
    """
    output_path = Path(output).resolve()
    vault_path = Path(vault_dir).resolve() if vault_dir else _get_vault_dir()

    if not vault_path.exists():
        print(f"[ERROR] Vault directory not found: {vault_path}", file=sys.stderr)
        sys.exit(1)

    print(f"Creating bundle from vault: {vault_path}")
    print(f"Output: {output_path}")

    with tempfile.TemporaryDirectory(prefix="tribunal-bundle-") as tmp:
        bundle_dir = Path(tmp) / "tribunal-bundle"
        bundle_dir.mkdir()

        # 1. Copy vault files
        vault_dest = bundle_dir / "vault"
        import shutil
        shutil.copytree(vault_path, vault_dest, dirs_exist_ok=True)
        print(f"  [+] Vault files: {vault_dest}")

        # 2. Requirements snapshot
        req_path = bundle_dir / "requirements.txt"
        try:
            result = subprocess.run(
                [sys.executable, "-m", "pip", "freeze"],
                capture_output=True,
                text=True,
                timeout=30,
            )
            req_path.write_text(result.stdout)
            print(f"  [+] Requirements snapshot: {len(result.stdout.splitlines())} packages")
        except Exception as exc:
            req_path.write_text(f"# pip freeze failed: {exc}\ntribunal\n")
            print(f"  [!] pip freeze failed: {exc}", file=sys.stderr)

        # 3. offline-install.sh script
        install_script = bundle_dir / "offline-install.sh"
        install_script.write_text(_OFFLINE_INSTALL_SCRIPT)
        install_script.chmod(0o755)
        print("  [+] offline-install.sh")

        # 4. Bundle metadata
        meta = {
            "created_at": __import__("datetime").datetime.utcnow().isoformat() + "Z",
            "vault_source": str(vault_path),
            "python_version": sys.version,
        }
        (bundle_dir / "bundle-meta.json").write_text(json.dumps(meta, indent=2))

        # 5. Pack into tar.gz
        with tarfile.open(output_path, "w:gz") as tar:
            tar.add(bundle_dir, arcname="tribunal-bundle")

    size_mb = output_path.stat().st_size / 1024 / 1024
    print(f"\n✅ Bundle created: {output_path} ({size_mb:.1f} MB)")
    print("   Transfer to air-gapped machine and run: bash tribunal-bundle/offline-install.sh")


_OFFLINE_INSTALL_SCRIPT = '''\
#!/usr/bin/env bash
# Tribunal offline installer — no network access required.
# Generated by: tribunal bundle
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VAULT_DIR="$SCRIPT_DIR/vault"
REQ_FILE="$SCRIPT_DIR/requirements.txt"

echo "=== Tribunal Offline Installer ==="
echo ""

# 1. Check Python
if ! command -v python3 &>/dev/null; then
  echo "[ERROR] python3 is required but not found." >&2
  exit 1
fi
echo "[+] Python: $(python3 --version)"

# 2. Install Python packages from requirements snapshot
if [[ -f "$REQ_FILE" ]]; then
  echo "[+] Installing Python packages (offline)..."
  python3 -m pip install --no-index --find-links . -r "$REQ_FILE" 2>/dev/null || \
    python3 -m pip install -r "$REQ_FILE" --quiet
fi

# 3. Install tribunal if available
if python3 -c "import launcher" &>/dev/null; then
  echo "[+] Tribunal launcher already installed."
else
  echo "[!] Tribunal launcher not found — install with: pip install tribunal" >&2
fi

# 4. Install vault files
PLUGIN_DIR="${CLAUDE_PLUGIN_DIR:-$HOME/.claude/tribunal}"
mkdir -p "$PLUGIN_DIR"
echo "[+] Installing vault to: $PLUGIN_DIR"
cp -r "$VAULT_DIR/." "$PLUGIN_DIR/"
echo "[+] Vault installed."

echo ""
echo "=== Installation complete ==="
echo "    Run: tribunal --help"
'''
