"""Bullish Momentum Scan — deteksi early bullish breakout momentum semua coin.

Menggunakan BullishScreener.scan_all_coins_sse() yang menjalankan
full 31-algorithm TradingEngine per coin untuk mendeteksi fase:
  - EARLY_BULLISH : awal breakout, potensi rally besar
  - PEAK_BULLISH  : momentum kuat tapi mungkin sudah dekat puncak
  - NOT_BULLISH   : belum ada sinyal bullish yang signifikan

Hasil disimpan ke tabel BullishMomentumScore di database.

Ini adalah versi CLI dari tombol "Bullish Momentum Scan" di halaman /admin/ml.

Usage:
    # Scan semua coin (timeframe 1D)
    python3 scripts/scan_bullish_momentum.py

    # Timeframe tertentu
    python3 scripts/scan_bullish_momentum.py --timeframe 4h

    # Quiet mode (untuk cron)
    python3 scripts/scan_bullish_momentum.py --quiet

Cron example:
    # Scan momentum setiap 6 jam
    0 */6 * * * cd /path && .venv/bin/python scripts/scan_bullish_momentum.py --quiet >> logs/scan_bullish.log 2>&1
"""
from __future__ import annotations

import argparse
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()


def main():
    parser = argparse.ArgumentParser(
        description='Deteksi early bullish breakout momentum semua coin',
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument('--timeframe', default='1D',
                        choices=['1m', '15m', '30m', '1h', '4h', '1D', '1W'],
                        help='OHLCV timeframe (default: 1D)')
    parser.add_argument('--asset-type', default='stock',
                        choices=['crypto', 'stock', 'stock_us'],
                        help='Asset type (default: stock)')
    parser.add_argument('--quiet', '-q', action='store_true',
                        help='Quiet — hanya summary')
    args = parser.parse_args()

    from app import create_app
    app = create_app()

    with app.app_context(), app.test_request_context():
        from flask import session
        session['asset_mode'] = args.asset_type
        from app.helpers.market_db import switch_market_schema
        switch_market_schema(args.asset_type)
        from app.services.bullish_screener import BullishScreener

        screener = BullishScreener()
        scored = 0
        skipped = 0
        failed = 0
        early_count = 0
        total = 0
        start_time = time.time()

        if not args.quiet:
            print(f'\n🚀  Bullish Momentum Scan — timeframe: {args.timeframe}')
            print(f'{"─" * 70}')

        for event in screener.scan_all_coins_sse(args.timeframe):
            evt_type = event.get('type')

            if evt_type == 'start':
                total = event['total']
                if not args.quiet:
                    print(f'  {event["message"]}')
                    print()

            elif evt_type == 'scored':
                scored += 1
                phase = event.get('phase', '?')
                if phase == 'EARLY_BULLISH':
                    early_count += 1

                if not args.quiet:
                    sym = event.get('symbol', '?')
                    score = event.get('score', 0)
                    conditions = event.get('conditions', 0)
                    pct = event['processed'] / event['total'] * 100

                    if phase == 'EARLY_BULLISH':
                        icon = '🟢'
                    elif phase == 'PEAK_BULLISH':
                        icon = '🟡'
                    else:
                        icon = '⚪'

                    print(f'  {icon} [{event["processed"]}/{event["total"]}] '
                          f'{sym:<10} {phase:<16} score={score:<5.0f} '
                          f'conditions={conditions}/5  ({pct:.0f}%)')

            elif evt_type == 'skip':
                skipped += 1
                if not args.quiet:
                    sym = event.get('symbol', event.get('coin_id', '?'))
                    print(f'  ⊘  [{event["processed"]}/{event["total"]}] '
                          f'{sym:<10} — {event.get("reason", "skipped")}')

            elif evt_type == 'error':
                failed += 1
                if not args.quiet:
                    sym = event.get('symbol', event.get('name', '?'))
                    print(f'  ✗  [{event["processed"]}/{event["total"]}] '
                          f'{sym:<10} — {event.get("error", "error")}')

            elif evt_type == 'done':
                pass  # Summary printed below

        elapsed = time.time() - start_time
        mins = int(elapsed // 60)
        secs = int(elapsed % 60)

        print(f'\n{"═" * 70}')
        print(f'🚀  Bullish Momentum Scan Complete — {mins}m {secs}s')
        print(f'    Timeframe: {args.timeframe}  |  Scored: {scored}  |  '
              f'Skipped: {skipped}  |  Failed: {failed}  |  Total: {total}')
        print(f'    🟢 Early Bullish: {early_count}  |  '
              f'Other: {scored - early_count}')
        print(f'{"═" * 70}')

        sys.exit(1 if failed > total * 0.5 else 0)


if __name__ == '__main__':
    main()
