#!/usr/bin/env bash
#
# bootstrap.sh — Inizializzazione del kit harness per un progetto tenant
#
# Presuppone che i file ./vars.yaml (o ./.vars) e ./.env siano già presenti nella directory
# corrente (forniti dall'admin insieme a questo script):
# vars.yaml con TENANT_ID e KB_URL, .env con KB_API_KEY.
# Scarica l'ultimo bundle harness (o usa un archivio locale fornito con --local-zip),
# materializza la cartella harness/ ed esegue il setup iniziale.
# In assenza di --local-zip si autocancella a fine esecuzione.
#
# Struttura creata nel progetto:
#   progetto-x/
#   ├── vars.yaml
#   ├── .env
#   ├── bootstrap.sh     (si autocancella al termine se remoto)
#   ├── release/
#   │   ├── bin/wrapper.sh
#   │   ├── release.zip  (archivio dell'ultima release installata)
#   │   ├── .version     (JSON: {version, checksum, fetched_at})
#   │   ├── overrides/   (sostituzioni integrali applicate dal wrapper)
#   │   └── addons/      (append al contenuto di cwd/)
#   └── cwd/               (working directory di runtime)
#
set -euo pipefail

die() { echo "[bootstrap] ERRORE: $*" >&2; exit 1; }
warn() { echo "[bootstrap] ATTENZIONE: $*" >&2; }

LOCAL_ZIP=""
while [ $# -gt 0 ]; do
  case "$1" in
    --local-zip)
      shift
      [ $# -gt 0 ] || die "--local-zip richiede il percorso del file ZIP"
      LOCAL_ZIP="$1"
      ;;
    --local-zip=*)
      LOCAL_ZIP="${1#--local-zip=}"
      ;;
    *)
      warn "Argomento sconosciuto: $1"
      ;;
  esac
  shift
done

if [ -n "$LOCAL_ZIP" ]; then
  [ -f "$LOCAL_ZIP" ] || die "File ZIP locale non trovato: $LOCAL_ZIP"
  LOCAL_ZIP="$(realpath "$LOCAL_ZIP")"
fi

if [ ! -f ./vars.yaml ] && [ ! -f ./.vars ]; then
  die "File ./vars.yaml non trovato nella directory corrente. Deve essere fornito dall'admin insieme a bootstrap.sh."
fi
if [ ! -f ./.env ]; then
  die "File ./.env non trovato nella directory corrente. Deve essere fornito dall'admin insieme a bootstrap.sh."
fi

command -v python3 >/dev/null 2>&1 || die "python3 non installato."
python3 -c 'import yaml' 2>/dev/null || die "Modulo Python PyYAML assente (es. apt install python3-yaml oppure pip install pyyaml)."

VARS_FILE=""
if [ -f ./vars.yaml ]; then
  VARS_FILE="./vars.yaml"
else
  VARS_FILE="./.vars"
fi

eval "$(python3 -c '
import sys, yaml

def flatten_vars(data, prefix=""):
    out = {}
    if isinstance(data, dict):
        for k, v in data.items():
            key = f"{prefix}_{k}".strip("_").upper()
            if isinstance(v, dict):
                out.update(flatten_vars(v, key))
            elif isinstance(v, list):
                out[key] = ",".join(str(i) for i in v)
            elif v is not None:
                out[key] = str(v)
    return out

try:
    with open(sys.argv[1]) as f:
        data = yaml.safe_load(f)
        if isinstance(data, dict):
            flat = flatten_vars(data)
            for k, v in flat.items():
                val = str(v).replace("\"", "\\\"")
                print(f"export {k}=\"{val}\"")
except Exception:
    with open(sys.argv[1]) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#"):
                if ":" in line:
                    k, v = line.split(":", 1)
                    key = k.strip().upper()
                    print(f"export {key}=\"{v.strip().strip(chr(34)).strip(chr(39))}\"")
                elif "=" in line:
                    k, v = line.split("=", 1)
                    key = k.strip().upper()
                    print(f"export {key}=\"{v.strip().strip(chr(34)).strip(chr(39))}\"")
' "$VARS_FILE" 2>/dev/null)"

set -a
# shellcheck disable=SC1091
. ./.env
set +a

: "${TENANT_ID:?Variabile tenant_id mancante in vars.yaml}"

API_BASE="${MC2_API_BASE:-}"

command -v unzip >/dev/null 2>&1 || die "unzip non installato."

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT INT TERM

if [ -n "$LOCAL_ZIP" ]; then
  echo "[bootstrap] Tenant: ${TENANT_ID} — modalità locale disconnessa"
  echo "[bootstrap] Uso dello ZIP locale fornito: ${LOCAL_ZIP}"
  cp -f "$LOCAL_ZIP" "${TMP_DIR}/bundle.zip"
else
  : "${HARNESS_URL:?Variabile HARNESS_URL mancante in vars.yaml (canale di distribuzione del kit)}"
  : "${KB_URL:?Variabile KB_URL mancante in vars.yaml}"
  : "${KB_API_KEY:?Variabile KB_API_KEY mancante in .env}"
  command -v curl >/dev/null 2>&1 || die "curl non installato."
  echo "[bootstrap] Tenant: ${TENANT_ID} — distribuzione: ${HARNESS_URL}"
  echo "[bootstrap] Download dell'ultimo bundle harness..."
  curl -sf "${HARNESS_URL}${API_BASE}/harness/bundle" -o "${TMP_DIR}/bundle.zip" \
    || die "Download bundle fallito (HTTP != 200 da ${HARNESS_URL}${API_BASE}/harness/bundle). Verifica HARNESS_URL."
fi

if [ "$(head -c 2 "${TMP_DIR}/bundle.zip")" != "PK" ]; then
  die "La risposta a ${HARNESS_URL:-}${API_BASE}/harness/bundle non e' uno ZIP: HARNESS_URL errato. Nulla e' stato installato."
fi

echo "[bootstrap] Verifica integrità dello zip..."
unzip -tq "${TMP_DIR}/bundle.zip" >/dev/null || die "Bundle corrotto: estrazione di prova fallita."

mkdir -p release/bin release/overrides release/addons

echo "[bootstrap] Estrazione di wrapper.sh in release/bin/..."
unzip -q -o "${TMP_DIR}/bundle.zip" -d "${TMP_DIR}/extract"

# Solo wrapper.sh vive in release/bin/: e' l'unico script che deve
# sopravvivere alla ricostruzione di cwd/ (deve essere invocabile anche
# prima che cwd/ esista).
if [ -f "${TMP_DIR}/extract/bin/wrapper.sh" ]; then
  cp "${TMP_DIR}/extract/bin/wrapper.sh" release/bin/wrapper.sh
fi
chmod +x release/bin/wrapper.sh
cp -f "${TMP_DIR}/bundle.zip" release/release.zip

if [ -f "${TMP_DIR}/extract/QUICKSTART.md" ]; then
  cp -f "${TMP_DIR}/extract/QUICKSTART.md" ./QUICKSTART.md
  echo "[bootstrap] Guida QUICKSTART.md aggiornata nella root del progetto."
fi

if [ -f "${TMP_DIR}/extract/.env.example" ] && [ ! -f ./.env.example ]; then
  cp -f "${TMP_DIR}/extract/.env.example" ./.env.example
  echo "[bootstrap] File .env.example copiato nella root del progetto."
fi

if [ -f "${TMP_DIR}/extract/vars.yaml.example" ] && [ ! -f ./vars.yaml.example ]; then
  cp -f "${TMP_DIR}/extract/vars.yaml.example" ./vars.yaml.example
  echo "[bootstrap] File vars.yaml.example copiato nella root del progetto."
fi

if [ -d "${TMP_DIR}/extract/devcontainer" ]; then
  mkdir -p ./devcontainer
  (
    shopt -s nullglob dotglob 2>/dev/null || true
    for f in "${TMP_DIR}/extract/devcontainer"/*; do
      [ -e "$f" ] || continue
      fname="$(basename "$f")"
      [ "$fname" = "." ] || [ "$fname" = ".." ] && continue
      [ "$fname" = ".env" ] && continue
      if [ "$fname" = "cato-ca.pem" ] && [ -s "./devcontainer/cato-ca.pem" ]; then
        continue
      fi
      cp -rf "$f" "./devcontainer/$fname"
    done
  )
  chmod +x ./devcontainer/*.sh 2>/dev/null || true
  echo "[bootstrap] Configurazione devcontainer/ inizializzata nella root del progetto."
fi


# Registra la versione correntemente installata in release/.version
if [ -n "$LOCAL_ZIP" ]; then
  VERSION="$(basename "${LOCAL_ZIP}" .zip | sed -n 's/^mc2-harness-//p')"
  [ -n "$VERSION" ] || VERSION="$(unzip -p "${LOCAL_ZIP}" VERSION 2>/dev/null | tr -d '[:space:]')"
  [ -n "$VERSION" ] || VERSION="0"
  CHECKSUM="$(sha256sum "${TMP_DIR}/bundle.zip" | awk '{print $1}')"
  printf '{"version":"%s","checksum":"%s","fetched_at":%s}\n' "$VERSION" "$CHECKSUM" "$(date +%s)" > release/.version
  echo "[bootstrap] Release locale installata: ${VERSION}"
else
  VERSION=""
  CHECKSUM=""
  LATEST_JSON="$(curl -sf "${HARNESS_URL}${API_BASE}/harness/latest" 2>/dev/null || true)"
  if [ -n "$LATEST_JSON" ]; then
    VERSION="$(printf '%s' "$LATEST_JSON" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
    CHECKSUM="$(printf '%s' "$LATEST_JSON" | sed -n 's/.*"checksum"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
  fi
  if [ -z "$VERSION" ]; then
    VERSION="latest"
    CHECKSUM="$(sha256sum "${TMP_DIR}/bundle.zip" | awk '{print $1}')"
  fi
  printf '{"version":"%s","checksum":"%s","fetched_at":%s}\n' "$VERSION" "$CHECKSUM" "$(date +%s)" > release/.version
  echo "[bootstrap] Release installata: ${VERSION}"
fi

# Esegue il setup iniziale per materializzare harness/
if [ -n "$LOCAL_ZIP" ]; then
  echo "[bootstrap] Materializzazione iniziale di cwd/ con bundle locale..."
  ./release/bin/wrapper.sh setup --local-zip "$LOCAL_ZIP"
else
  echo "[bootstrap] Materializzazione iniziale di cwd/..."
  ./release/bin/wrapper.sh setup
fi

echo "[bootstrap] Bootstrap completato. Entrypoint: release/bin/wrapper.sh (comandi: setup, upgrade)"
echo "[bootstrap] Per iniziare: cd cwd && <tuo_comando_o_agente>"
if [ -f "$0" ] && [ "$(basename -- "$0")" = "bootstrap.sh" ] && [ -z "$LOCAL_ZIP" ]; then
  rm -f -- "$0"
fi