#!/usr/bin/env python3
"""
Iteration 24: Phase 3D Final Deployment Monitoring & Readiness Validation
2026-07-10 20:23 UTC

Verify all systems are ready for Phase 3D soft deployment:
- Config file integrity
- NPZ cache validity
- Live trading sessions
- Python 3.8 backtester availability
- Deployment directories writable
"""

import json
import os
import subprocess
from pathlib import Path
from datetime import datetime

def check_config_file():
    config_path = Path("/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/obw_platform/configs/h4_freedommoney_callback_tuned_v5.yaml")
    if config_path.exists():
        size = config_path.stat().st_size
        with open(config_path) as f:
            content = f.read()
        has_callback_tuning = "callbackPercent" in content
        return {
            "exists": True,
            "size_bytes": size,
            "has_callback_tuning": has_callback_tuning,
            "path": str(config_path)
        }
    return {"exists": False}

def check_npz_cache():
    cache_path = Path("/var/www/vps2.happyuser.info/top/veronika_htx_live_20260603/DB/freedommoney_bingx_1m_90d.npz")
    if cache_path.exists():
        size = cache_path.stat().st_size
        return {
            "exists": True,
            "size_bytes": size,
            "path": str(cache_path)
        }
    return {"exists": False}

def check_python38():
    try:
        result = subprocess.Popen(
            ["/var/www/vps2.happyuser.info/top/backtest_SK/.venv38/bin/python3", "--version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        out, err = result.communicate(timeout=5)
        version_str = (out.decode() if out else err.decode()).strip()
        return {
            "available": result.returncode == 0,
            "version": version_str,
            "path": "/var/www/vps2.happyuser.info/top/backtest_SK/.venv38/bin/python3"
        }
    except Exception as e:
        return {"available": False, "error": str(e)}

def check_live_sessions():
    try:
        result = subprocess.Popen(
            ["pgrep", "-a", "python"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        out, _ = result.communicate(timeout=5)
        lines = out.decode().strip().split('\n') if out else []

        sessions = []
        for line in lines:
            if any(x in line for x in ["callme", "hype", "paper_live"]):
                parts = line.split(None, 1)
                if len(parts) >= 2:
                    sessions.append({
                        "pid": parts[0],
                        "running": True
                    })

        return {
            "count": len(sessions),
            "sessions": sessions,
            "expected": 6  # At least 6 should be running
        }
    except Exception as e:
        return {"error": str(e)}

def check_deployment_dirs():
    dirs = {
        "phase_3a": "/var/www/vps2.happyuser.info/top/top_1/obw_platform/_reports/_live/freedommoney_phase3a_phase3a_soft_deployment_20260710T200400Z",
        "phase_3d": "/var/www/vps2.happyuser.info/top/top_1/obw_platform/_reports/_live/freedommoney_phase3d_phase3d_soft_deployment_20260710T200900Z"
    }

    results = {}
    for name, path in dirs.items():
        p = Path(path)
        results[name] = {
            "exists": p.exists(),
            "path": path,
            "writable": os.access(str(p), os.W_OK) if p.exists() else False
        }

    return results

def main():
    timestamp = datetime.utcnow().isoformat() + "Z"

    result = {
        "iteration": 24,
        "timestamp": timestamp,
        "phase": "3D_final_monitoring",
        "checks": {
            "config_file": check_config_file(),
            "npz_cache": check_npz_cache(),
            "python38": check_python38(),
            "live_sessions": check_live_sessions(),
            "deployment_dirs": check_deployment_dirs()
        }
    }

    # Overall readiness assessment
    config_ok = result["checks"]["config_file"].get("exists", False)
    npz_ok = result["checks"]["npz_cache"].get("exists", False)
    python38_ok = result["checks"]["python38"].get("available", False)
    live_ok = result["checks"]["live_sessions"].get("count", 0) >= 6

    result["overall_status"] = "GREENLIGHT" if all([config_ok, npz_ok, python38_ok, live_ok]) else "DEGRADED"
    result["deployment_approved"] = all([config_ok, npz_ok, python38_ok, live_ok])

    print(json.dumps(result, indent=2))

    # Write to file
    report_dir = Path("/var/www/vps2.happyuser.info/top/top_1/obw_platform/_reports/_live/freedommoney_phase3d_phase3d_soft_deployment_20260710T200900Z")
    if not report_dir.exists():
        report_dir.mkdir(parents=True, exist_ok=True)

    report_file = report_dir / "iter24_final_monitoring.json"
    with open(report_file, 'w') as f:
        json.dump(result, f, indent=2)

    print(f"\n✅ Monitoring report saved: {report_file}")
    print(f"Overall Status: {result['overall_status']}")
    print(f"Deployment Approved: {result['deployment_approved']}")

if __name__ == "__main__":
    main()
