#!/usr/bin/env python3
"""Check V9 optimization progress."""

import sqlite3
import numpy as np
from pathlib import Path

DB_PATH = Path(__file__).parent / "3_results" / "study.db"
TARGET_WS = 218.26  # V7 best


def main():
    if not DB_PATH.exists():
        print("No database found - optimization not started yet")
        return

    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    cursor.execute('SELECT COUNT(*) FROM trials')
    total = cursor.fetchone()[0]

    if total == 0:
        print("No trials completed yet")
        conn.close()
        return

    # Get all trial data
    cursor.execute('''
    SELECT t.trial_id, tv.value as ws
    FROM trials t
    JOIN trial_values tv ON t.trial_id = tv.trial_id
    ORDER BY t.trial_id
    ''')
    trials = cursor.fetchall()

    ws_values = []
    mass_values = []
    wfe40_values = []
    wfe60_values = []
    mfg90_values = []
    feasible_count = 0
    best_ws = float('inf')
    best_trial = None
    best_mass = None

    for trial_id, ws in trials:
        cursor.execute('SELECT key, value_json FROM trial_user_attributes WHERE trial_id = ?', (trial_id,))
        attrs = {r[0]: r[1].strip('"') for r in cursor.fetchall()}

        mass = float(attrs.get('mass_kg', '999'))
        wfe40 = float(attrs.get('obj_wfe_40_20', '0'))
        wfe60 = float(attrs.get('obj_wfe_60_20', '0'))
        mfg90 = float(attrs.get('obj_mfg_90', '0'))

        ws_values.append(ws)
        mass_values.append(mass)
        wfe40_values.append(wfe40)
        wfe60_values.append(wfe60)
        mfg90_values.append(mfg90)

        if mass <= 120:
            feasible_count += 1
            if ws < best_ws:
                best_ws = ws
                best_trial = trial_id
                best_mass = mass

    conn.close()

    # Print results
    print("=" * 60)
    print("V9 SAT v3 OPTIMIZATION STATUS")
    print("=" * 60)
    print(f"Trials completed: {total}")
    feas_pct = 100.0 * feasible_count / total
    print(f"Feasible trials: {feasible_count} ({feas_pct:.1f}%)")
    print()

    print(f"Best WS: {best_ws:.2f} (trial {best_trial})")
    print(f"Best mass: {best_mass:.2f} kg" if best_mass else "")
    print(f"Target: {TARGET_WS} (V7 best)")
    print()

    gap = best_ws - TARGET_WS
    if gap < 0:
        print(f"*** BEATING TARGET by {-gap:.2f}! ***")
    elif gap == 0:
        print("*** MATCHED TARGET! ***")
    else:
        print(f"Gap to target: {gap:.2f}")

    print()
    print("Mass distribution:")
    print(f"  Min: {min(mass_values):.2f} kg")
    print(f"  Max: {max(mass_values):.2f} kg")
    print(f"  Mean: {np.mean(mass_values):.2f} kg")

    # WS progression
    print()
    print("WS progression (last 15):")
    start_idx = max(0, len(ws_values) - 15)
    for i in range(start_idx, len(ws_values)):
        ws = ws_values[i]
        mass = mass_values[i]
        marker = " *** BEST" if ws == best_ws else ""
        feas = "F" if mass <= 120 else "X"
        print(f"  Trial {i+1:3d}: WS={ws:8.2f} mass={mass:6.2f}kg [{feas}]{marker}")

    # Phase analysis
    print()
    print("Performance by phase:")
    phases = [
        ("Phase 1 (1-30)", 0, 30),
        ("Phase 2 (31-80)", 30, 80),
        ("Phase 3 (81-190)", 80, 190),
        ("L-BFGS (191-200)", 190, 200),
    ]
    for name, start, end in phases:
        phase_ws = ws_values[start:min(end, len(ws_values))]
        if phase_ws:
            phase_mass = mass_values[start:min(end, len(mass_values))]
            feasible_ws = [w for w, m in zip(phase_ws, phase_mass) if m <= 120]
            if feasible_ws:
                print(f"  {name}: {len(phase_ws):3d} trials, best={min(feasible_ws):.2f}, mean={np.mean(feasible_ws):.2f}")
            else:
                print(f"  {name}: {len(phase_ws):3d} trials, no feasible")

    # Comparison
    print()
    print("=" * 60)
    print("CAMPAIGN COMPARISON")
    print("=" * 60)
    print(f"  V6 (TPE):     225.41")
    print(f"  V7 (SAT v1):  218.26")
    print(f"  V8 (SAT v2):  271.38")
    print(f"  V9 (SAT v3):  {best_ws:.2f}")
    print()
    if best_ws < TARGET_WS:
        print(f"  V9 is the NEW BEST! Improved by {TARGET_WS - best_ws:.2f}")
    elif best_ws < 225.41:
        print(f"  V9 beats V6 but not V7")
    else:
        print(f"  V9 still searching...")


if __name__ == "__main__":
    main()
