#!/bin/bash
set -euo pipefail

PKG_DIR="$(cd "$(dirname "$0")" && pwd)"
ACCOUNT_ID=""
REPAIR_ONLY=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --account)
      ACCOUNT_ID="${2:-}"
      shift 2
      ;;
    --repair-only|--repair)
      REPAIR_ONLY=1
      shift
      ;;
    *)
      echo "Unknown argument: $1"
      exit 2
      ;;
  esac
done

ACCOUNTS_DIR="$HOME/.accio/accounts"
if [[ ! -d "$ACCOUNTS_DIR" ]]; then
  echo "Accio Work account directory not found: $ACCOUNTS_DIR"
  exit 1
fi

if [[ -z "$ACCOUNT_ID" ]]; then
  ACCOUNTS=()
  while IFS= read -r ACCOUNT_NAME; do
    [[ -n "$ACCOUNT_NAME" ]] && ACCOUNTS+=("$ACCOUNT_NAME")
  done < <(find "$ACCOUNTS_DIR" -mindepth 1 -maxdepth 1 -type d -exec basename {} \; | sort)
  if [[ "${#ACCOUNTS[@]}" -eq 1 ]]; then
    ACCOUNT_ID="${ACCOUNTS[0]}"
  else
    echo "Multiple Accio Work accounts found. Pass --account <account_id>."
    printf '%s
' "${ACCOUNTS[@]}"
    exit 1
  fi
fi

TARGET="$ACCOUNTS_DIR/$ACCOUNT_ID"
BACKUP_ROOT="$HOME/.accio/aios-install-backups"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="$BACKUP_ROOT/$ACCOUNT_ID-aios-before-sitefix-$STAMP"
mkdir -p "$BACKUP_ROOT"

python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode local --report "$PKG_DIR/reports/install-macos-local-$STAMP.json"

if [[ "$REPAIR_ONLY" == "1" ]]; then
  python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode repair --target "$TARGET" --report "$PKG_DIR/reports/install-macos-repair-$STAMP.json"
  python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode verify --target "$TARGET" --report "$PKG_DIR/reports/install-macos-verify-$STAMP.json"
  echo "AIOS Accio Work package repaired."
  echo "Target: $TARGET"
  exit 0
fi

python3 - "$PKG_DIR" "$TARGET" "$BACKUP" "$BACKUP_ROOT/$ACCOUNT_ID-non-aios-snapshot-$STAMP.json" <<'PY'
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path

pkg = Path(sys.argv[1])
target = Path(sys.argv[2])
backup = Path(sys.argv[3])
snapshot_path = Path(sys.argv[4])
manifest = json.loads((pkg / "manifest.json").read_text(encoding="utf-8"))
agent_ids = [(a.get("target_dir") or a.get("id")) for a in manifest.get("agents", [])]
skill_ids = [s.get("id") for s in manifest.get("skills", [])]
root_files = [
    "manifest.json",
    "00-先打开我-安装与启动说明.md",
    "01-Windows-双击安装.cmd",
    "02-Windows-高级安装-PowerShell.ps1",
    "03-macOS-双击安装.command",
    "04-安装后复制到AccioWork的首跑指令.md",
    "05-商家白皮书-安装前先看.html",
    "05-商家白皮书-安装前先看.md",
    "06-Windows-修复智能体.cmd",
    "install-macos.command",
    "install-windows.ps1",
    "install-windows-nopython.ps1",
    "install-windows-double-click.cmd",
    "repair-aios-agents.cmd",
    "validate_install.py",
]
rels = [*(f"agents/{x}" for x in agent_ids), *(f"skills/{x}" for x in skill_ids)]
rels += ["runtime-tools", "bindings", "checksums", "workspaces/国际站商家AI交付包", "harness", "manuals", *root_files]
backup.mkdir(parents=True, exist_ok=True)
copied = []
for rel in rels:
    src = target / rel
    if not src.exists():
        continue
    dst = backup / rel
    dst.parent.mkdir(parents=True, exist_ok=True)
    if src.is_dir():
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(src, dst)
    else:
        shutil.copy2(src, dst)
    copied.append(rel)

def non_aios(path, allowed):
    if not path.exists():
        return []
    return sorted(p.name for p in path.iterdir() if p.is_dir() and p.name not in allowed)

snapshot = {
    "created_at": datetime.now(timezone.utc).isoformat(),
    "policy": "non-AIOS content is preserved in place; metadata only, no recursive account backup",
    "target": str(target),
    "backup": str(backup),
    "backed_up_paths": copied,
    "non_aios_agents": non_aios(target / "agents", set(agent_ids)),
    "non_aios_skills": non_aios(target / "skills", set(skill_ids)),
}
snapshot_path.write_text(json.dumps(snapshot, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
PY

python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode apply --target "$TARGET" --report "$PKG_DIR/reports/install-macos-apply-$STAMP.json"
python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode verify --target "$TARGET" --report "$PKG_DIR/reports/install-macos-verify-$STAMP.json"

echo "AIOS Accio Work package installed."
echo "Target: $TARGET"
echo "Backup: $BACKUP"
