"""
Test script untuk AlphaX Pattern Detection
===========================================
Test pattern detection dengan sample data untuk verify semua components working.
"""

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

import pandas as pd
import yfinance as yf
from alphax import (
    detect_all_bullish_patterns,
    calc_choppiness,
    calc_htf_bias,
    calc_atr
)

def test_pattern_detection():
    """Test pattern detection dengan real stock data"""
    print("=" * 60)
    print("Testing AlphaX Pattern Detection")
    print("=" * 60)

    # Test dengan beberapa saham IDX
    test_tickers = [
        "BBCA.JK",  # Bank Central Asia - liquid, blue chip
        "BBRI.JK",  # Bank BRI
        "TLKM.JK",  # Telkom Indonesia
    ]

    for ticker in test_tickers:
        print(f"\n{'=' * 60}")
        print(f"Testing {ticker}")
        print(f"{'=' * 60}")

        try:
            # Download data
            df = yf.download(ticker, period="2y", interval="1d", progress=False)

            # Normalize yfinance MultiIndex columns
            if isinstance(df.columns, pd.MultiIndex):
                df.columns = df.columns.droplevel(1)

            if len(df) < 100:
                print(f"[SKIP] Insufficient data: {len(df)} bars")
                continue

            # Set ticker attribute
            df.attrs['ticker'] = ticker

            print(f"Data: {len(df)} bars")
            print(f"Date range: {df.index[0].date()} to {df.index[-1].date()}")

            current_price = df['Close'].iloc[-1]
            print(f"Current price: {current_price:.2f}")

            # Test ATR
            atr = calc_atr(df, 14)
            atr_value = atr.iloc[-1]
            print(f"ATR(14): {atr_value:.2f}")

            # Test Choppiness Index
            chop_idx = calc_choppiness(df, 14)
            print(f"Choppiness Index: {chop_idx:.1f} ({'Choppy' if chop_idx > 62 else 'Trending'})")

            # Test HTF Bias
            try:
                htf_bias = calc_htf_bias(df, '1wk', 21, 55)
                print(f"HTF Bias: {htf_bias['trend']}")
            except Exception as e:
                print(f"HTF Bias: Error - {e}")

            # Test Pattern Detection
            print(f"\nRunning pattern detection...")
            pattern = detect_all_bullish_patterns(
                df,
                left_lb=10,
                right_lb=10,
                max_pivots=500,
                min_confluence=5,
                htf_timeframe='1wk',
                htf_fast=21,
                htf_slow=55,
                chop_max=62.0,
                min_rr=1.5
            )

            if pattern.detected:
                print(f"\n✅ PATTERN DETECTED!")
                print(f"   Name: {pattern.name}")
                print(f"   Bullish: {pattern.is_bullish}")
                print(f"   Entry: {pattern.entry_price:.2f}")
                print(f"   Stop: {pattern.stop_price:.2f}")
                print(f"   Target: {pattern.target_price:.2f}")

                if pattern.entry_price > 0 and pattern.stop_price > 0:
                    rr = abs(pattern.target_price - pattern.entry_price) / abs(pattern.entry_price - pattern.stop_price)
                    print(f"   R:R Ratio: {rr:.2f}")
            else:
                print(f"\n❌ No bullish pattern detected (or below confluence threshold)")

        except Exception as e:
            print(f"[ERROR] Failed to test {ticker}: {e}")
            import traceback
            traceback.print_exc()

    print(f"\n{'=' * 60}")
    print("Test completed!")
    print(f"{'=' * 60}")


def test_pivot_detection():
    """Test pivot detection specifically"""
    print("\n" + "=" * 60)
    print("Testing Pivot Detection")
    print("=" * 60)

    ticker = "BBCA.JK"
    df = yf.download(ticker, period="1y", interval="1d", progress=False)

    # Normalize yfinance MultiIndex columns: ('Close', 'BBCA.JK') -> 'Close'
    if isinstance(df.columns, pd.MultiIndex):
        df.columns = df.columns.droplevel(1)

    print(f"Columns after normalize: {df.columns.tolist()}")

    df.attrs['ticker'] = ticker

    from alphax import collect_pivots

    pivot_highs, pivot_lows = collect_pivots(df, left_lb=10, right_lb=10, max_history=500)

    print(f"Pivot Highs detected: {len(pivot_highs)}")
    if pivot_highs:
        print(f"   Most recent: Index {pivot_highs[0].index}, Price {pivot_highs[0].price:.2f}")
        if len(pivot_highs) > 1:
            print(f"   Second: Index {pivot_highs[1].index}, Price {pivot_highs[1].price:.2f}")

    print(f"Pivot Lows detected: {len(pivot_lows)}")
    if pivot_lows:
        print(f"   Most recent: Index {pivot_lows[0].index}, Price {pivot_lows[0].price:.2f}")
        if len(pivot_lows) > 1:
            print(f"   Second: Index {pivot_lows[1].index}, Price {pivot_lows[1].price:.2f}")


if __name__ == "__main__":
    test_pivot_detection()
    test_pattern_detection()
