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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RISK_FILE="$ROOT/config/risk_governor_rules.json"
RISK_BACKUP="$ROOT/config/risk_governor_rules.json.bak"

cp "$RISK_FILE" "$RISK_BACKUP"
trap 'mv "$RISK_BACKUP" "$RISK_FILE"' EXIT

python3 "$ROOT/ops/check_configs.py"
python3 "$ROOT/src/pipeline.py" \
  --source file \
  --symbol XAUUSD \
  --timeframe M5 \
  --execution-mode file \
  --input-path "$ROOT/data/inbox/request.json" \
  --output-path "$ROOT/data/outbox/signal.json" \
  --execution-report-path "$ROOT/data/inbox/execution_report.json" \
  --poll-seconds 1 \
  --enable-incident-autofix true \
  --once

python3 "$ROOT/src/chat_tuning.py" \
  --role admin \
  --channel feishu \
  --text "把最小置信度改为0.7" \
  --approved true \
  --tenant-id smoke

CONTROL_PORT=8792
CONTROL_TOKEN=smoke-token
CONTROL_LOG="$ROOT/logs/control_api_smoke.log"

python3 "$ROOT/src/control_api.py" --host 127.0.0.1 --port "$CONTROL_PORT" --token "$CONTROL_TOKEN" > "$CONTROL_LOG" 2>&1 &
CONTROL_PID=$!
trap 'kill "$CONTROL_PID" 2>/dev/null || true; mv "$RISK_BACKUP" "$RISK_FILE"' EXIT
sleep 1

python3 - <<PY
import json, urllib.request
base = "http://127.0.0.1:${CONTROL_PORT}"
health = json.loads(urllib.request.urlopen(base + "/health", timeout=3).read().decode("utf-8"))
assert health.get("ok") is True
req = urllib.request.Request(
    base + "/tune",
    data=json.dumps({"role":"admin","channel":"feishu","text":"把最小置信度改为0.7","approved":True}).encode("utf-8"),
    headers={"Content-Type":"application/json","X-Api-Key":"${CONTROL_TOKEN}","X-Tenant":"smoke_api"},
)
tune = json.loads(urllib.request.urlopen(req, timeout=3).read().decode("utf-8"))
assert tune.get("ok") is True
audit_req = urllib.request.Request(
    base + "/audit/export?tenant_id=smoke_api&limit=10",
    headers={"X-Api-Key":"${CONTROL_TOKEN}"},
)
audit = json.loads(urllib.request.urlopen(audit_req, timeout=3).read().decode("utf-8"))
assert audit.get("ok") is True
assert isinstance(audit.get("records"), list)
metrics_req = urllib.request.Request(
    base + "/runtime/metrics?tenant_id=smoke_api",
    headers={"X-Api-Key":"${CONTROL_TOKEN}"},
)
metrics = json.loads(urllib.request.urlopen(metrics_req, timeout=3).read().decode("utf-8"))
assert metrics.get("ok") is True
snap_create = urllib.request.Request(
    base + "/config/snapshot/create",
    data=json.dumps({"tenant_id":"smoke_api","reason":"smoke_test"}).encode("utf-8"),
    headers={"Content-Type":"application/json","X-Api-Key":"${CONTROL_TOKEN}"},
)
snap = json.loads(urllib.request.urlopen(snap_create, timeout=3).read().decode("utf-8"))
assert snap.get("ok") is True
tag = snap.get("snapshot", {}).get("tag", "")
assert tag
snap_list_req = urllib.request.Request(
    base + "/config/snapshot/list",
    data=json.dumps({"tenant_id":"smoke_api"}).encode("utf-8"),
    headers={"Content-Type":"application/json","X-Api-Key":"${CONTROL_TOKEN}"},
)
snap_list = json.loads(urllib.request.urlopen(snap_list_req, timeout=3).read().decode("utf-8"))
assert snap_list.get("ok") is True
snap_rb_req = urllib.request.Request(
    base + "/config/snapshot/rollback",
    data=json.dumps({"tenant_id":"smoke_api","tag":tag}).encode("utf-8"),
    headers={"Content-Type":"application/json","X-Api-Key":"${CONTROL_TOKEN}"},
)
snap_rb = json.loads(urllib.request.urlopen(snap_rb_req, timeout=3).read().decode("utf-8"))
assert snap_rb.get("ok") is True
PY

kill "$CONTROL_PID" 2>/dev/null || true

echo "e2e smoke passed"
