#!/usr/bin/env python3
"""
Iteration 9: Validate pending config variants on 90d FREEDOMMONEY crash regime.
Use Python 3.8+ environment to work around infrastructure constraint.
"""
import sys
import os
sys.path.insert(0, '/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/obw_platform')

import numpy as np
import yaml
from backtester_dual_core_dynamic_v5_fast_pack import simulate

NPZ_PATH = '/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/DB/freedommoney_bingx_1m_90d.npz'
CONFIG_DIR = '/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/obw_platform/configs'

PENDING_VARIANTS = [
    'h4_freedommoney_aggressive_short_v4.yaml',
    'h4_freedommoney_capped_long_v5.yaml',
    'h4_freedommoney_callback_tuned_v5.yaml',
    'h4_freedommoney_dca_conservative_v6.yaml',
]

BASELINE_CONFIG = 'h4_freedommoney_short_focused_long_tight_v4.yaml'
BASELINE_RATIO = 1.78

results = []

# Load baseline for comparison
baseline_path = os.path.join(CONFIG_DIR, BASELINE_CONFIG)
with open(baseline_path) as f:
    baseline_config = yaml.safe_load(f)
print(f"Baseline config loaded: {BASELINE_CONFIG} (expected ratio: {BASELINE_RATIO})")
print("=" * 80)

# Test each pending variant
for config_name in PENDING_VARIANTS:
    config_path = os.path.join(CONFIG_DIR, config_name)
    if not os.path.exists(config_path):
        print(f"SKIP: {config_name} not found")
        continue

    try:
        with open(config_path) as f:
            config = yaml.safe_load(f)

        # Load NPZ
        data = np.load(NPZ_PATH, allow_pickle=True)
        bars = data['bars']
        trends = data['trends']

        # Run simulation
        state = simulate(
            bars=bars,
            trends=trends,
            strategy_params_long=config['strategy_params_long'],
            strategy_params_short=config['strategy_params_short'],
            symbol='FREEDOMMONEY/USDT',
            timeframe='1m',
            initial_equity_per_leg=config['initial_equity_per_leg'],
            fee_rate=config['fee_rate'],
            funding_rate_per_8h_bps=config['funding_rate_per_8h_bps'],
            slippage_per_side=config['slippage_per_side'],
        )

        mtm_pnl = state['mtm_pnl']
        mtm_dd_pct = state['mtm_dd_pct']
        ratio = mtm_pnl / abs(mtm_dd_pct) if mtm_dd_pct != 0 else 0
        unrealized = state['unrealized']
        margin_calls = state['margin_calls']
        trades = state['total_trades']

        status = "PASS" if margin_calls <= 2 and unrealized >= -60 else "FAIL"
        constraint_ok = "✓" if (margin_calls <= 2 and unrealized >= -60) else "✗"

        result_line = (
            f"{config_name:45} | "
            f"ratio {ratio:6.2f} | "
            f"MTM {mtm_pnl:8.2f} | "
            f"DD {mtm_dd_pct:7.2f}% | "
            f"unrealized {unrealized:7.2f} | "
            f"margin_calls {margin_calls:2d} | "
            f"trades {trades:5d} | "
            f"{status} {constraint_ok}"
        )
        print(result_line)
        results.append((config_name, ratio, mtm_pnl, mtm_dd_pct, unrealized, margin_calls, trades, status))

    except Exception as e:
        print(f"{config_name:45} | ERROR: {str(e)[:60]}")

print("=" * 80)
print(f"Baseline ({BASELINE_CONFIG}): ratio {BASELINE_RATIO:.2f}")
print()

# Summary
if results:
    best = max(results, key=lambda x: x[1])
    print(f"Best new variant: {best[0]} with ratio {best[1]:.2f}")
    if best[1] > BASELINE_RATIO:
        print(f"  → IMPROVEMENT: +{best[1]-BASELINE_RATIO:.2f} ratio points vs baseline")
    else:
        print(f"  → REGRESSION: -{BASELINE_RATIO-best[1]:.2f} ratio points vs baseline")
