"""
prediction_log.py — Logs gap predictions and grades them against actual results.
v1.0.0

Usage:
    ~/pdmp/venv/bin/python prediction_log.py --log       # Run at 15:45 (logs tomorrow's prediction)
    ~/pdmp/venv/bin/python prediction_log.py --grade     # Run at 09:16 (grades today's actual gap)
    ~/pdmp/venv/bin/python prediction_log.py --report    # View accuracy report
    ~/pdmp/venv/bin/python prediction_log.py --backfill  # (Optional) Grade past days
"""
import sqlite3
import argparse
from datetime import datetime, timedelta
import sys

# Add pdmp directory to path to import day_before_buildup
sys.path.insert(0, '/home/dinkstrade/pdmp')
from day_before_buildup import analyze

DB_PATH = '/home/dinkstrade/pdmp/sentiment_history.db'

def init_db():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS prediction_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            log_date TEXT NOT NULL,           -- The date we made the prediction (e.g., Nov 2)
            target_date TEXT NOT NULL,        -- The day being predicted (e.g., Nov 3)
            prediction TEXT NOT NULL,         -- STRONG GAP UP, GAP UP, FLAT, etc.
            confidence TEXT NOT NULL,         -- HIGH, MEDIUM, LOW
            bull_score INTEGER,
            bear_score INTEGER,
            reasons TEXT,                     -- JSON string of signals
            actual_gap REAL,                  -- Filled in the next morning
            actual_direction TEXT,            -- Filled in the next morning
            is_correct INTEGER,               -- 1 = correct, 0 = wrong, NULL = not graded yet
            graded_at TEXT,                   -- When it was graded
            UNIQUE(log_date, target_date)
        )
    """)
    conn.commit()
    conn.close()

def log_prediction():
    """Run at 15:45. Predicts gap for the next trading day."""
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    now = datetime.now()
    # Target is the next weekday
    target = now + timedelta(days=1)
    while target.weekday() >= 5:
        target += timedelta(days=1)
    
    log_date_str = now.strftime('%Y-%m-%d')
    target_date_str = target.strftime('%Y-%m-%d')
    
    print(f"🔮 Generating prediction for {target_date_str} (based on {log_date_str} data)...")
    
    # Use day_before_buildup.analyze() to get the prediction
    result = analyze(target_date_str, symbol='NIFTY')
    
    if 'error' in result:
        print(f"❌ Failed: {result['error']}")
        return
    
    pred = result.get('prediction')
    if not pred:
        print("❌ No prediction generated (missing data)")
        return
        
    prediction = pred['prediction']
    confidence = pred['confidence']
    bull_score = pred['bull_score']
    bear_score = pred['bear_score']
    
    # Save to DB
    try:
        c.execute("""
            INSERT OR REPLACE INTO prediction_log 
            (log_date, target_date, prediction, confidence, bull_score, bear_score, reasons)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """, (
            log_date_str, target_date_str, prediction, confidence,
            bull_score, bear_score, '|'.join(pred['reasons'])
        ))
        conn.commit()
        print(f"✅ Logged: {prediction} ({confidence} confidence)")
        print(f"   Bull score: {bull_score}, Bear score: {bear_score}")
        print(f"   Target date: {target_date_str}")
    except Exception as e:
        print(f"❌ DB Error: {e}")
    finally:
        conn.close()

def grade_prediction():
    """Run at 09:16. Grades yesterday's prediction against today's actual gap."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    
    today = datetime.now().strftime('%Y-%m-%d')
    yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    
    # Find ungraded predictions where target_date is today or earlier
    rows = c.execute("""
        SELECT * FROM prediction_log 
        WHERE target_date <= ? AND actual_gap IS NULL
    """, (today,)).fetchall()
    
    if not rows:
        print(f"Nothing to grade for {today}.")
        conn.close()
        return
        
    for row in rows:
        target_date = row['target_date']
        
        # Get first and last snapshot for the target date
        first = c.execute("""
            SELECT spot, snapshot_at FROM intraday_levels_history 
            WHERE symbol='NIFTY' AND date=? ORDER BY snapshot_at ASC LIMIT 1
        """, (target_date,)).fetchone()
        
        # Get last snapshot from prior trading day (walk back)
        prior = c.execute("""
            SELECT spot, date FROM intraday_levels_history 
            WHERE symbol='NIFTY' AND date < ? ORDER BY date DESC, snapshot_at DESC LIMIT 1
        """, (target_date,)).fetchone()
        
        if not first or not prior:
            print(f"⚠️  Cannot grade {target_date} — missing snapshots.")
            continue
        
        gap = round(first['spot'] - prior['spot'], 2)
        
        # Classify actual direction (matching prediction thresholds)
        if gap > 50:
            actual = "GAP UP"
        elif gap < -50:
            actual = "GAP DOWN"
        else:
            actual = "FLAT"
            
        # Grade: does prediction and actual match in direction?
        pred_dir = "UP" if "UP" in row['prediction'] else ("DOWN" if "DOWN" in row['prediction'] else "FLAT")
        act_dir = "UP" if "UP" in actual else ("DOWN" if "DOWN" in actual else "FLAT")
        
        is_correct = 1 if pred_dir == act_dir else 0
        
        # Update DB
        c.execute("""
            UPDATE prediction_log 
            SET actual_gap=?, actual_direction=?, is_correct=?, graded_at=?
            WHERE id=?
        """, (gap, actual, is_correct, datetime.now().isoformat(), row['id']))
        
        conn.commit()
        
        result = "✅ CORRECT" if is_correct else "❌ WRONG"
        print(f"📊 Graded {target_date}: {result}")
        print(f"   Prediction: {row['prediction']}")
        print(f"   Reality: {actual} ({gap:+.2f} pts)")
    
    conn.close()

def report():
    """Print accuracy report."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    
    rows = c.execute("""
        SELECT * FROM prediction_log 
        WHERE is_correct IS NOT NULL 
        ORDER BY target_date DESC
    """).fetchall()
    conn.close()
    
    if not rows:
        print("No graded predictions yet.")
        return
    
    total = len(rows)
    correct = sum(1 for r in rows if r['is_correct'] == 1)
    accuracy = (correct / total) * 100
    
    print(f"\n{'='*60}")
    print(f"  PREDICTION ACCURACY REPORT")
    print(f"{'='*60}")
    print(f"  Total graded:   {total}")
    print(f"  Correct:        {correct}")
    print(f"  Wrong:          {total - correct}")
    print(f"  Accuracy:       {accuracy:.1f}%")
    print(f"{'='*60}\n")
    
    # By confidence
    print("  By Confidence Level:")
    for conf in ['HIGH', 'MEDIUM', 'LOW']:
        group = [r for r in rows if r['confidence'] == conf]
        if group:
            correct_g = sum(1 for r in group if r['is_correct'] == 1)
            acc = (correct_g / len(group)) * 100
            print(f"    {conf}: {correct_g}/{len(group)} ({acc:.0f}%)")
    
    print("\n  Recent predictions:")
    for r in rows[:10]:
        icon = "✅" if r['is_correct'] == 1 else "❌"
        print(f"    {icon} {r['target_date']}: Predicted '{r['prediction']}' ({r['confidence']}) → {r['actual_direction']} ({r['actual_gap']:+.1f})")
    print()

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--log', action='store_true', help='Log today prediction for tomorrow')
    ap.add_argument('--grade', action='store_true', help='Grade ungraded predictions')
    ap.add_argument('--report', action='store_true', help='Show accuracy report')
    args = ap.parse_args()
    
    init_db()
    
    if args.log:
        log_prediction()
    elif args.grade:
        grade_prediction()
    elif args.report:
        report()
    else:
        print("Usage: prediction_log.py --log | --grade | --report")

if __name__ == '__main__':
    main()
