#!/usr/bin/env python3
"""
Check signal outcomes by monitoring current prices.

Every run:
1. Get current price for each asset
2. Check active signals for target/stop hits
3. Update signal outcomes
4. Calculate performance metrics
"""

import json
import sqlite3
from pathlib import Path
from datetime import datetime


def get_current_price(asset: str) -> float:
    """Get current price from latest signal summary."""

    summary_file = Path(f'/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/realtime_summary_{asset}.json')

    if not summary_file.exists():
        return None

    with open(summary_file) as f:
        data = json.load(f)

    return data.get('current_price')


def check_active_signals():
    """Check all active signals for outcomes."""

    db_path = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/data/signal_performance.db')

    if not db_path.exists():
        print("No signal database found")
        return

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

    # Get all active signals
    cursor.execute('''
        SELECT id, asset, entry_price, target_price, stop_price, direction
        FROM signals
        WHERE status = 'active'
        ORDER BY entry_time DESC
    ''')

    active_signals = cursor.fetchall()

    if not active_signals:
        print("No active signals to check")
        conn.close()
        return

    print(f"Checking {len(active_signals)} active signals...")
    print("-"*80)

    closed_count = 0

    for signal_id, asset, entry_price, target_price, stop_price, direction in active_signals:
        # Get current price
        current_price = get_current_price(asset)

        if current_price is None:
            print(f"{asset.upper()} (#{signal_id}): Unable to get current price")
            continue

        # Check outcome
        outcome = None
        outcome_price = current_price

        if direction == 'bullish':
            if current_price >= target_price:
                outcome = 'win'
            elif current_price <= stop_price:
                outcome = 'loss'
        else:  # bearish
            if current_price <= target_price:
                outcome = 'win'
            elif current_price >= stop_price:
                outcome = 'loss'

        if outcome:
            # Calculate profit/loss
            if direction == 'bullish':
                profit_loss = current_price - entry_price
            else:
                profit_loss = entry_price - current_price

            # Close signal
            cursor.execute('''
                UPDATE signals
                SET outcome = ?, outcome_time = ?, outcome_price = ?,
                    profit_loss = ?, status = 'closed'
                WHERE id = ?
            ''', (outcome, datetime.now().isoformat(), current_price, profit_loss, signal_id))

            closed_count += 1

            # Calculate time held
            cursor.execute('SELECT entry_time FROM signals WHERE id = ?', (signal_id,))
            entry_time = datetime.fromisoformat(cursor.fetchone()[0])
            time_held = (datetime.now() - entry_time).total_seconds() / 60  # minutes

            print(f"{asset.upper()} (#{signal_id}): {outcome.upper()}")
            print(f"  Entry: ${entry_price:.2f} → {outcome} at ${current_price:.2f}")
            print(f"  P/L: ${profit_loss:.2f} | Time: {time_held:.0f} min")
        else:
            # Still active - calculate progress
            if direction == 'bullish':
                progress = ((current_price - entry_price) / (target_price - entry_price)) * 100
            else:
                progress = ((entry_price - current_price) / (entry_price - target_price)) * 100

            progress = max(-100, min(100, progress))  # Clamp between -100% and 100%

            print(f"{asset.upper()} (#{signal_id}): ACTIVE ({progress:+.0f}% to target)")
            print(f"  Entry: ${entry_price:.2f} | Current: ${current_price:.2f}")
            print(f"  Target: ${target_price:.2f} | Stop: ${stop_price:.2f}")

    conn.commit()
    conn.close()

    print("-"*80)
    print(f"✓ Closed {closed_count} signals")

    # Update performance summary
    update_performance_summary()


def update_performance_summary():
    """Update performance metrics."""

    db_path = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/data/signal_performance.db')
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute('''
        SELECT asset, signal_type, direction,
               COUNT(*) as total,
               SUM(CASE WHEN outcome = 'win' THEN 1 ELSE 0 END) as wins,
               SUM(CASE WHEN outcome = 'loss' THEN 1 ELSE 0 END) as losses
        FROM signals
        WHERE status = 'closed'
        GROUP BY asset, signal_type, direction
    ''')

    rows = cursor.fetchall()

    for row in rows:
        asset, signal_type, direction, total, wins, losses = row
        win_rate = (wins / total * 100) if total > 0 else 0

        cursor.execute('''
            INSERT OR REPLACE INTO performance_summary
            (asset, signal_type, direction, total_signals, wins, losses, win_rate, last_updated)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ''', (asset, signal_type, direction, total, wins, losses, win_rate, datetime.now().isoformat()))

    conn.commit()
    conn.close()


def get_performance_summary() -> dict:
    """Get current performance metrics."""

    db_path = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/data/signal_performance.db')

    if not db_path.exists():
        return {'message': 'No performance data yet'}

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

    # Overall stats
    cursor.execute('''
        SELECT
            COUNT(*) as total,
            SUM(CASE WHEN outcome = 'win' THEN 1 ELSE 0 END) as wins,
            SUM(CASE WHEN outcome = 'loss' THEN 1 ELSE 0 END) as losses,
            AVG(CASE WHEN outcome = 'win' THEN profit_loss END) as avg_win,
            AVG(CASE WHEN outcome = 'loss' THEN profit_loss END) as avg_loss
        FROM signals
        WHERE status = 'closed'
    ''')

    row = cursor.fetchone()

    if not row or row[0] == 0:
        conn.close()
        return {'total_signals': 0}

    total, wins, losses, avg_win, avg_loss = row
    win_rate = (wins / total * 100) if total > 0 else 0

    summary = {
        'total_signals': total,
        'wins': wins,
        'losses': losses,
        'win_rate': round(win_rate, 1),
        'avg_win': round(avg_win, 2) if avg_win else 0,
        'avg_loss': round(avg_loss, 2) if avg_loss else 0,
        'profit_factor': round(abs(avg_win / avg_loss), 2) if avg_loss and avg_win else 0
    }

    # By asset
    cursor.execute('''
        SELECT asset, COUNT(*) as total, SUM(CASE WHEN outcome = 'win' THEN 1 ELSE 0 END) as wins
        FROM signals
        WHERE status = 'closed'
        GROUP BY asset
    ''')

    summary['by_asset'] = []
    for row in cursor.fetchall():
        asset, total, wins = row
        win_rate = (wins / total * 100) if total > 0 else 0
        summary['by_asset'].append({
            'asset': asset,
            'total': total,
            'wins': wins,
            'win_rate': round(win_rate, 1)
        })

    # By signal type
    cursor.execute('''
        SELECT signal_type, COUNT(*) as total, SUM(CASE WHEN outcome = 'win' THEN 1 ELSE 0 END) as wins
        FROM signals
        WHERE status = 'closed'
        GROUP BY signal_type
    ''')

    summary['by_type'] = []
    for row in cursor.fetchall():
        signal_type, total, wins = row
        win_rate = (wins / total * 100) if total > 0 else 0
        summary['by_type'].append({
            'type': signal_type,
            'total': total,
            'wins': wins,
            'win_rate': round(win_rate, 1)
        })

    # By direction
    cursor.execute('''
        SELECT direction, COUNT(*) as total, SUM(CASE WHEN outcome = 'win' THEN 1 ELSE 0 END) as wins
        FROM signals
        WHERE status = 'closed'
        GROUP BY direction
    ''')

    summary['by_direction'] = []
    for row in cursor.fetchall():
        direction, total, wins = row
        win_rate = (wins / total * 100) if total > 0 else 0
        summary['by_direction'].append({
            'direction': direction,
            'total': total,
            'wins': wins,
            'win_rate': round(win_rate, 1)
        })

    conn.close()
    return summary


def main():
    """Main execution."""

    print("="*80)
    print("SIGNAL OUTCOME CHECKER")
    print("="*80)
    print()

    # Check active signals
    check_active_signals()

    # Get performance summary
    print("\n" + "="*80)
    print("PERFORMANCE SUMMARY")
    print("="*80)

    summary = get_performance_summary()

    if summary.get('total_signals') == 0:
        print("\nNo closed signals yet")
        print("📊 Waiting for signals to hit target/stop...")
    else:
        print(f"\nTotal Signals: {summary['total_signals']}")
        print(f"Wins: {summary['wins']} | Losses: {summary['losses']}")
        print(f"Win Rate: {summary['win_rate']}%")
        print(f"Avg Win: ${summary['avg_win']} | Avg Loss: ${summary['avg_loss']}")
        print(f"Profit Factor: {summary['profit_factor']}")

        if summary['by_asset']:
            print("\nBy Asset:")
            for asset in summary['by_asset']:
                print(f"  {asset['asset'].upper()}: {asset['win_rate']}% ({asset['wins']}/{asset['total']})")

        if summary['by_type']:
            print("\nBy Signal Type:")
            for sig_type in summary['by_type']:
                print(f"  {sig_type['type']}: {sig_type['win_rate']}% ({sig_type['wins']}/{sig_type['total']})")

        if summary['by_direction']:
            print("\nBy Direction:")
            for direction in summary['by_direction']:
                print(f"  {direction.upper()}: {direction['win_rate']}% ({direction['wins']}/{direction['total']})")

    print("\n" + "="*80)
    print("✓ Done!")
    print("="*80)


if __name__ == "__main__":
    main()
