#!/usr/bin/env bash
# AISLE local operator kit. Requires curl and python3.
set -euo pipefail

BASE="${1:-https://sauce-ops.appskins-studio.workers.dev}"
INTO="${2:-./aisle-local}"
BASE="${BASE%/}"
KIT="$(cd "$(dirname "$0")" && pwd)"

echo "AISLE local operator kit"
echo "source : $BASE"
echo "target : $INTO"
echo ""

mkdir -p "$INTO"

python3 - "$KIT/manifest.json" "$BASE" "$INTO" <<'PY'
import json, os, sys, urllib.request

manifest, base, into = sys.argv[1], sys.argv[2], sys.argv[3]
with open(manifest, encoding='utf-8') as fh:
    items = json.load(fh)['files']
failed = []
for f in items:
    dest = os.path.join(into, f['dest'])
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    try:
        with urllib.request.urlopen(base + f['path'], timeout=120) as r:
            data = r.read()
        if len(data) < int(f['minBytes']):
            raise ValueError(f'short file: {len(data)} < {f["minBytes"]}')
        with open(dest, 'wb') as out:
            out.write(data)
        print(f'  ok  {f["dest"]:<34} {len(data):>9} bytes')
    except Exception as e:
        failed.append(f'{f["path"]}: {e}')
        print(f'  FAIL {f["path"]}')

for name in ('README.md', 'brief.template.md', 'acceptance-criteria.json', 'config.example.json'):
    with open(os.path.join(os.path.dirname(manifest), name), 'rb') as src:
        with open(os.path.join(into, name), 'wb') as out:
            out.write(src.read())

with open(os.path.join(os.path.dirname(manifest), 'config.example.json'), encoding='utf-8') as fh:
    cfg = json.load(fh)
cfg['base'] = base
from datetime import datetime, timezone
cfg['installed_at'] = datetime.now(timezone.utc).isoformat()
with open(os.path.join(into, 'config.json'), 'w', encoding='utf-8') as fh:
    json.dump(cfg, fh, indent=2)

if failed:
    print(f'LOCAL SETUP INCOMPLETE ({len(failed)} failed)')
    for f in failed:
        print('  ' + f)
    sys.exit(1)
print('LOCAL SETUP VERIFIED')
print(f'Open {into}/README.md for the team runbook.')
PY
