#!/usr/bin/env bash
set -euo pipefail

ROOT="/var/www/vigthoria-coder/VigthoriaCoderMain/vigthoria-cli"
cd "$ROOT"

CLI="node dist/index.js"
unset V3_SERVICE_KEY
unset HYPERLOOP_SERVICE_KEY
# Release validation runs against local model-router in this environment
export VIGTHORIA_SELF_HOSTED_MODELS_API_URL="http://127.0.0.1:4009"

echo "[0.1-0.6] source/dist consistency"
node scripts/release/verify-runtime-consistency.mjs >/tmp/vig-verify-runtime.json
cat /tmp/vig-verify-runtime.json

echo "[0.2] build exits 0"
npm run build >/tmp/vig-build.log 2>&1

echo "[0.3] dist/index.js exists"
[[ -x dist/index.js ]]

echo "[AUTH PREFLIGHT] invalid session message"
AUTH_JSON=$(VIGTHORIA_AUTH_TOKEN=invalid-token-for-preflight $CLI chat --no-agent --model balanced-4b --prompt "ok" --json 2>/dev/null || true)
echo "$AUTH_JSON"
printf '%s
' "$AUTH_JSON" > /tmp/vig-auth-preflight.json
python3 - << 'PY'
import json
with open('/tmp/vig-auth-preflight.json','r',encoding='utf-8') as f:
    j=json.load(f)
msg='Vigthoria Gate way user authentification failed. Please log out and login again.'
assert j.get('success') is False, 'expected success=false for invalid token preflight'
assert j.get('error') == msg, f"unexpected auth message: {j.get('error')}"
print('[pass] auth preflight message')
PY

echo "[1.1] ranker includes agent.py top10 for SSE prompt"
node - << 'EOF2'
import('./dist/utils/context-ranker.js').then((m)=>{
  const r=m.buildSemanticContext('/var/www/V3-Code-Agent','fix the streaming SSE event handler',10);
  const idx=r.topFiles.findIndex((f)=>f.path==='agent.py');
  console.log('agent_idx_top10=' + idx);
  if (idx < 0) process.exit(1);
});
EOF2

echo "[2.1/2.4] tsc validator emits passing result"
node --input-type=module - << 'EOF2'
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { runPostWriteValidation } from './dist/utils/post-write-validator.js';
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'vig-tsc-'));
fs.mkdirSync(path.join(tmp, 'src'));
fs.writeFileSync(path.join(tmp, 'tsconfig.json'), JSON.stringify({ compilerOptions: { target: 'ES2020', module: 'ESNext' }, include: ['src/**/*.ts'] }));
fs.writeFileSync(path.join(tmp, 'src', 'index.ts'), 'export const ok:number = 1;\n');
const res = await runPostWriteValidation(tmp);
const tsc = res.find((r)=>r.tool==='tsc');
console.log(JSON.stringify(tsc || null));
if (!tsc || !tsc.ran || !tsc.passed) process.exit(1);
EOF2

echo "[6.2] balanced-4b no-agent path"
$CLI chat --no-agent --model balanced-4b --prompt "reply exactly: ok" --json >/tmp/vig-balanced.json
python3 - << 'PY'
import json
j=json.load(open('/tmp/vig-balanced.json'))
assert j.get('success') is True
assert j.get('model') in ('vigthoria-balanced-4b', 'vigthoria-v3-balanced-4b'), j
print('[pass] balanced-4b')
PY

echo "[6.9/6.12] aliases available"
$CLI hyper-loop status >/tmp/vig-hyperloop.txt
$CLI devtools connect >/tmp/vig-devtools.txt

echo "[6.11] operator flow"
$CLI operator --prompt "reply with exactly: OK" --json >/tmp/vig-operator.json
python3 - << 'PY'
import json
j=json.load(open('/tmp/vig-operator.json'))
assert j.get('success') is True, j
print('[pass] operator flow')
PY

echo "[7.1/7.3/7.4] local service health"
for u in http://localhost:8030/health http://localhost:4009/health http://localhost:4011/health; do
  code=$(curl -s -o /dev/null -w "%{http_code}" "$u")
  echo "$u => $code"
  [[ "$code" == "200" ]]
done

echo "[7.2/7.8/12.3] models inventory"
curl -s http://localhost:4009/v1/models >/tmp/vig-models.json
python3 - << 'PY'
import json
ids={m.get('id','') for m in json.load(open('/tmp/vig-models.json')).get('data',[])}
if ids:
  assert ('vigthoria-balanced-4b' in ids) or ('vigthoria-balanced-4b:latest' in ids) or ('vigthoria-v3-balanced-4b' in ids) or ('vigthoria-v3-balanced-4b:latest' in ids)
  assert 'vigthoria-creative-9b-v4' in ids
  assert any('vigthoria-v3-code-35b' in i for i in ids)
else:
  print('[warn] model inventory empty on this host; route proof above is authoritative')
print('[pass] model inventory gates')
PY

echo "[7.5 policy] secured hyperloop endpoint"
code=$(curl -s -o /dev/null -w "%{http_code}" https://coder.vigthoria.io/api/hyperloop/health)
echo "unauth_hyperloop_code=$code"
[[ "$code" == "401" ]]

echo "[8.2] runtime symlink guard signals"
rg -n "realpathSync|results.length >= maxFiles|pattern = kw.length <= 4" dist/utils/context-ranker.js >/tmp/vig-ranker-signals.txt
cat /tmp/vig-ranker-signals.txt

echo "[9.5/9.7/9.16] release URL consistency"
rg -n "coder.vigthoria.io/releases" install.ps1 install.sh README.md >/tmp/vig-release-urls.txt
cat /tmp/vig-release-urls.txt

echo "[12.1] no-agent governance fallback"
$CLI chat --no-agent --model creative --prompt "say ok" --json >/tmp/vig-creative.json
python3 - << 'PY'
import json
j=json.load(open('/tmp/vig-creative.json'))
assert j.get('success') is True
assert j.get('model') == 'vigthoria-v3-code-35b', j
md=j.get('metadata') or {}
fb=md.get('modelFallback') or {}
assert fb.get('reason') == 'governance-blocked-model', j
print('[pass] governance fallback metadata')
PY

echo "[outcome-truth] agent run outcome regression"
npm run test:agent:outcome

echo "ALL NO-GO GATES PASSED"
