"""
Demo runner — generates synthetic Nifty-like OHLCV data and runs the full
Phase 1 pipeline (indicators + candlestick patterns + price action + confidence
engine) end to end, so you can see real output without needing broker access.

Swap `generate_synthetic_ohlcv()` for a real CSV (yfinance / your mStock
historical data dump) once you're ready — the rest of the pipeline doesn't
change.

Run: python demo.py
"""

import numpy as np
import pandas as pd

from core.confidence_engine import calculate_confidence
from core import indicators as ind
from core import candlestick_patterns as candles
from core import price_action as pa


def generate_synthetic_ohlcv(n=300, start_price=22000, seed=42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    dates = pd.date_range("2025-01-01", periods=n, freq="5min")

    # random walk with mild upward drift + occasional trend legs, to make
    # structure/BOS detection produce something meaningful
    returns = rng.normal(loc=0.0003, scale=0.002, size=n)
    trend_leg = np.sin(np.linspace(0, 6, n)) * 0.001
    close = start_price * np.cumprod(1 + returns + trend_leg)

    high = close * (1 + np.abs(rng.normal(0, 0.0015, n)))
    low = close * (1 - np.abs(rng.normal(0, 0.0015, n)))
    open_ = close + rng.normal(0, 0.001, n) * close
    volume = rng.integers(50000, 500000, n)

    df = pd.DataFrame(
        {"open": open_, "high": high, "low": low, "close": close, "volume": volume},
        index=dates,
    )
    # ensure OHLC consistency
    df["high"] = df[["open", "close", "high"]].max(axis=1)
    df["low"] = df[["open", "close", "low"]].min(axis=1)
    return df


def main():
    df = generate_synthetic_ohlcv()
    print(f"Loaded {len(df)} bars, {df.index[0]} to {df.index[-1]}\n")

    print("=" * 70)
    print("INDICATORS (latest values)")
    print("=" * 70)
    all_ind = ind.compute_all(df)
    print(f"EMA(50): {all_ind['ema_50'].iloc[-1]:.2f}")
    print(f"RSI: {all_ind['rsi'].iloc[-1]:.2f}")
    print(f"ADX: {all_ind['adx']['adx'].iloc[-1]:.2f}")
    print(f"Supertrend direction: {'UP' if all_ind['supertrend']['trend'].iloc[-1] == 1 else 'DOWN'}")
    print(f"ATR: {all_ind['atr'].iloc[-1]:.2f}")

    print("\n" + "=" * 70)
    print("CANDLESTICK PATTERNS (last bar)")
    print("=" * 70)
    print(candles.latest_signal(df) or "No pattern fired on latest bar")

    print("\n" + "=" * 70)
    print("PRICE ACTION / MARKET STRUCTURE")
    print("=" * 70)
    pa_summary = pa.analyze(df)
    print(f"Trend: {pa_summary['trend']}")
    print(f"Bias: {pa_summary['bias']}")
    print(f"Last BOS: {pa_summary['last_bos']}")
    print(f"Last CHoCH: {pa_summary['last_choch']}")
    print(f"Liquidity sweeps (recent): {len(pa_summary['liquidity_sweeps'])}")
    print(f"Fair Value Gaps (recent): {len(pa_summary['fvgs'])}")

    print("\n" + "=" * 70)
    print("CONFIDENCE ENGINE DECISION")
    print("=" * 70)
    # option_chain / news / global_market scores default to 0 until those
    # modules exist (Phase 4+) — pass sample values here just to show the
    # engine's full behavior once they're wired in.
    decision = calculate_confidence(
        df, symbol="NIFTY50",
        option_chain_score=0,
        news_score=0,
        global_market_score=0,
    )
    print(decision.summary())

    print("\n" + "=" * 70)
    print("SAME DECISION WITH SAMPLE OPTION/NEWS/GLOBAL SCORES (illustrative)")
    print("=" * 70)
    decision2 = calculate_confidence(
        df, symbol="NIFTY50",
        option_chain_score=80,
        news_score=70,
        global_market_score=90,
    )
    print(decision2.summary())


if __name__ == "__main__":
    main()
