#!/usr/bin/env python3
"""
Iteration 21: Phase 3D Soft Deployment Monitor
Executes callback_tuned_v5 config on FREEDOMMONEY 90d data with 1-5% allocation simulation.
Monitors first 24 hours of trading metrics against backtest predictions.
"""

import sys
import json
import os
from datetime import datetime
from pathlib import Path

sys.path.insert(0, '/var/www/vps2.happyuser.info/top/backtest_SK')
sys.path.insert(0, '/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603')

import numpy as np
from obw_platform.backtester_dual_long_short_fast_pack_v2 import BacktesterFastPack

# Phase 3D deployment parameters
ALLOCATION_PCT = 0.03  # 3% initial allocation
BACKTEST_EXPECTED_RATIO = 2.49
BACKTEST_EXPECTED_MTM = 108.86
BACKTEST_EXPECTED_MC = 0
BACKTEST_EXPECTED_UNREALIZED = -21.24
BACKTEST_EXPECTED_DD = -43.67

# Monitoring thresholds
MC_HARD_LIMIT = 2
UNREALIZED_HARD_LIMIT = -60.0
PNL_TOLERANCE_PCT = 0.15  # ±15% acceptable

def load_config_yaml(path):
    import yaml
    with open(path, 'r') as f:
        return yaml.safe_load(f)

def simulate_hours(npz_path, hours=2):
    """Simulate first N hours of trading (60 bars per hour at 1m timeframe)."""
    bars_to_run = min(hours * 60, 500)  # Cap at 500 bars for speed

    try:
        data = np.load(npz_path, allow_pickle=True)
        ohlcv = data['ohlcv']
        print(f"[Phase 3D] Loaded NPZ: {len(ohlcv)} total bars available")

        # Extract first N bars
        ohlcv_subset = ohlcv[:bars_to_run]

        # Simulate with callback_tuned_v5 config
        config = load_config_yaml('/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/obw_platform/configs/h4_freedommoney_callback_tuned_v5.yaml')

        bt = BacktesterFastPack(config=config)
        results = bt.simulate_bars(
            ohlcv_subset,
            symbol='FREEDOMMONEY/USDT:USDT',
            symbol_decimals=5
        )

        return {
            'bars_simulated': len(ohlcv_subset),
            'hours_simulated': len(ohlcv_subset) / 60.0,
            'equity': results.get('final_equity', 0),
            'unrealized': results.get('unrealized_pnl', 0),
            'margin_calls': results.get('margin_calls', 0),
            'dd_pct': results.get('dd_pct', 0),
            'mtm_pnl': results.get('mtm_pnl', 0),
            'trades': results.get('trades', 0),
            'results_full': results
        }
    except Exception as e:
        print(f"[Phase 3D] Simulation failed: {e}", file=sys.stderr)
        raise

def validate_deployment(phase3d_results):
    """Validate Phase 3D results against backtest predictions."""
    issues = []

    mc = phase3d_results['margin_calls']
    unrealized = phase3d_results['unrealized']
    mtm = phase3d_results.get('mtm_pnl', 0)

    # Hard constraints
    if mc > MC_HARD_LIMIT:
        issues.append(f"FAIL: Margin calls {mc} > limit {MC_HARD_LIMIT}")

    if unrealized < UNREALIZED_HARD_LIMIT:
        issues.append(f"FAIL: Unrealized {unrealized} < limit {UNREALIZED_HARD_LIMIT}")

    # Soft constraints (tolerance checks)
    if mtm != 0:
        pnl_pct_diff = abs(mtm - BACKTEST_EXPECTED_MTM) / abs(BACKTEST_EXPECTED_MTM)
        if pnl_pct_diff > PNL_TOLERANCE_PCT:
            issues.append(f"WARN: MTM PnL {mtm} differs {pnl_pct_diff*100:.1f}% from expected {BACKTEST_EXPECTED_MTM}")

    return issues

def main():
    deployment_dir = Path('/var/www/vps2.happyuser.info/top/top_1/obw_platform/_reports/_live/freedommoney_phase3d_phase3d_soft_deployment_20260710T200900Z')
    deployment_dir.mkdir(parents=True, exist_ok=True)

    print(f"[Phase 3D] Starting deployment monitor...")
    print(f"[Phase 3D] Config: h4_freedommoney_callback_tuned_v5.yaml")
    print(f"[Phase 3D] Allocation: {ALLOCATION_PCT*100:.1f}%")
    print(f"[Phase 3D] Test window: First 2 hours (120 bars at 1m)")
    print()

    # Run simulation
    try:
        results = simulate_hours(
            '/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/DB/freedommoney_bingx_1m_90d.npz',
            hours=2
        )

        print(f"[Phase 3D] Simulation completed:")
        print(f"  Bars: {results['bars_simulated']}")
        print(f"  Hours: {results['hours_simulated']:.2f}")
        print(f"  Equity: ${results['equity']:.2f}")
        print(f"  Unrealized: ${results['unrealized']:.2f}")
        print(f"  Margin calls: {results['margin_calls']}")
        print(f"  DD%: {results['dd_pct']:.2f}%")
        print(f"  MTM PnL: ${results.get('mtm_pnl', 0):.2f}")
        print(f"  Trades: {results['trades']}")
        print()

        # Validate
        issues = validate_deployment(results)
        if issues:
            print("[Phase 3D] Validation issues found:")
            for issue in issues:
                print(f"  {issue}")
        else:
            print("[Phase 3D] ✓ All validation checks PASSED")

        # Save results
        results_json = {
            'timestamp': datetime.utcnow().isoformat(),
            'phase': '3D',
            'allocation_pct': ALLOCATION_PCT,
            'results': results,
            'validation_issues': issues,
            'status': 'PASS' if not any(i.startswith('FAIL') for i in issues) else 'FAIL'
        }

        with open(deployment_dir / 'phase3d_iter21_monitor.json', 'w') as f:
            json.dump(results_json, f, indent=2, default=str)

        print(f"\n[Phase 3D] Results saved to {deployment_dir / 'phase3d_iter21_monitor.json'}")

        return 0 if results_json['status'] == 'PASS' else 1

    except Exception as e:
        print(f"[Phase 3D] ERROR: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        return 1

if __name__ == '__main__':
    sys.exit(main())
