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

ROOT="${ROOT:-/var/www/vps2.happyuser.info/dex}"
cd "$ROOT"

OUT_DIR="DEX_REPORTS/live_check_manual_25"
mkdir -p "$OUT_DIR"

TS="$(date -u +%Y%m%dT%H%M%SZ)"
ENTRY_MD="$OUT_DIR/ENTRY_${TS}.md"
LEDGER="$OUT_DIR/manual_live_entries.jsonl"

echo "Paste tx_hash:"
read -r TX_HASH

echo "Paste position_id / NFT id if known, else press Enter:"
read -r POSITION_ID

echo "Paste wallet address, or happyuser.base.eth if not resolved yet:"
read -r WALLET

cat > "$ENTRY_MD" <<EOM
# CHECK/USDC manual live entry

created_utc: ${TS}

wallet: ${WALLET}
tx_hash: ${TX_HASH}
position_id: ${POSITION_ID}

pool: USDC/CHECK Concentrated 500
pool_address: 0x5a7b4970b2610aee4776a6944d9f2171ee6060b0
network: Base

strategy: check_regime_router / bull_wide_70_40_72h
capital_target_usd: 25

deposited_usdc: 18.60
deposited_check: 160.15
deposit_total_usd_est: 24.81
gas_usd_est: 0.01

range_format: CHECK per USDC
range_low_check_per_usdc: 18.49
range_high_check_per_usdc: 82.87

server_reference:
  fresh_npz: DEX_DATA/fast_npz/base_CHECK_USDC_2PCT_fresh_fee_replay_v2.npz
  router_report: DEX_REPORTS/paper_live_check_regime_router_v1/latest/summary.csv
  router_decision: DEX_REPORTS/paper_live_check_regime_router_v1/latest_decision.json

Exit rules:
- exit/rebalance if router route != bull_wide_70_40_72h
- exit/rebalance if position goes out of range
- exit if estimated live loss <= -10% of $25
- do not increase size before 3-7 days of evidence
- no private key on server
- no auto-signed transactions
EOM

python3 - <<PY
import json
from pathlib import Path

entry = {
    "created_utc": "${TS}",
    "wallet": "${WALLET}",
    "tx_hash": "${TX_HASH}",
    "position_id": "${POSITION_ID}",
    "network": "Base",
    "pool": "USDC/CHECK Concentrated 500",
    "pool_address": "0x5a7b4970b2610aee4776a6944d9f2171ee6060b0",
    "strategy": "check_regime_router / bull_wide_70_40_72h",
    "capital_target_usd": 25,
    "deposited_usdc": 18.60,
    "deposited_check": 160.15,
    "deposit_total_usd_est": 24.81,
    "gas_usd_est": 0.01,
    "range_format": "CHECK per USDC",
    "range_low_check_per_usdc": 18.49,
    "range_high_check_per_usdc": 82.87,
    "status": "OPEN_MANUAL_LIVE"
}

Path("${LEDGER}").parent.mkdir(parents=True, exist_ok=True)
with open("${LEDGER}", "a") as f:
    f.write(json.dumps(entry, ensure_ascii=False) + "\\n")
PY

cp DEX_REPORTS/paper_live_check_regime_router_v1/latest_decision.json \
   "$OUT_DIR/router_decision_at_entry_${TS}.json" 2>/dev/null || true

cp DEX_REPORTS/paper_live_check_regime_router_v1/latest/summary.csv \
   "$OUT_DIR/router_summary_at_entry_${TS}.csv" 2>/dev/null || true

echo "[written] $ENTRY_MD"
echo "[appended] $LEDGER"
