"""
weekly_signal_frequency_v1.py
==============================
Shows the real distribution of weekly signal frequency
so we can set honest expectations for the live system.

Run from project root on home machine:
  python src/research/weekly_signal_frequency_v1.py
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys

BASE_PATH = Path(__file__).resolve().parents[2]
SRC_PATH  = BASE_PATH / "src"
if str(SRC_PATH) not in sys.path:
    sys.path.append(str(SRC_PATH))

TRADES_DIR = BASE_PATH / "data" / "processed" / "trades"

def main():
    print("=" * 65)
    print("WEEKLY SIGNAL FREQUENCY — HONEST DISTRIBUTION")
    print("=" * 65)

    # Load trade log
    trade_log = None
    for fname in ["trades_real_costs.csv", "trades_eurusd_final.csv"]:
        p = TRADES_DIR / fname
        if p.exists():
            trade_log = pd.read_csv(p, parse_dates=["entry_time"])
            print(f"\n  Loaded: {fname}  ({len(trade_log):,} trades)")
            break

    if trade_log is None:
        print("ERROR: No trade log found")
        return

    # Group trades by week
    trade_log["week"] = trade_log["entry_time"].dt.to_period("W")
    trade_log["year"] = trade_log["entry_time"].dt.year
    trade_log["month"] = trade_log["entry_time"].dt.to_period("M")

    weekly_counts = trade_log.groupby("week").size()

    # How many total weeks in the backtest period
    all_weeks = pd.period_range(
        start=trade_log["entry_time"].min(),
        end=trade_log["entry_time"].max(),
        freq="W"
    )
    total_weeks = len(all_weeks)

    # Weeks with zero trades (no signal that week)
    weeks_with_trades = len(weekly_counts)
    weeks_zero = total_weeks - weeks_with_trades
    weeks_zero_pct = weeks_zero / total_weeks * 100

    print(f"\n  Total weeks in backtest : {total_weeks}")
    print(f"  Weeks with 0 trades     : {weeks_zero} ({weeks_zero_pct:.0f}%)")
    print(f"  Weeks with 1+ trades    : {weeks_with_trades} ({100-weeks_zero_pct:.0f}%)")
    print(f"  Avg trades/week (all)   : {len(trade_log)/total_weeks:.1f}")
    print(f"  Avg trades/week (active): {weekly_counts.mean():.1f}")

    print(f"\n  {'─'*55}")
    print(f"  WEEKLY TRADE COUNT DISTRIBUTION")
    print(f"  {'─'*55}")

    # Count distribution including zero weeks
    all_weekly = pd.Series(0, index=all_weeks)
    for w, cnt in weekly_counts.items():
        if w in all_weekly.index:
            all_weekly[w] = cnt

    dist = all_weekly.value_counts().sort_index()
    for trades, count in dist.items():
        pct = count / total_weeks * 100
        bar = "█" * int(pct / 2)
        print(f"  {trades:>2} trades/week : {count:>4} weeks  ({pct:>5.1f}%)  {bar}")

    print(f"\n  {'─'*55}")
    print(f"  CONSECUTIVE ZERO-TRADE WEEKS")
    print(f"  {'─'*55}")

    # Find longest streaks of zero-trade weeks
    streaks = []
    current = 0
    for w in all_weeks:
        if all_weekly[w] == 0:
            current += 1
        else:
            if current > 0:
                streaks.append(current)
            current = 0
    if current > 0:
        streaks.append(current)

    if streaks:
        print(f"  Longest zero streak : {max(streaks)} consecutive weeks")
        print(f"  Avg zero streak     : {np.mean(streaks):.1f} weeks")
        print(f"  Streaks of 1 week   : {sum(1 for s in streaks if s==1)}")
        print(f"  Streaks of 2 weeks  : {sum(1 for s in streaks if s==2)}")
        print(f"  Streaks of 3+ weeks : {sum(1 for s in streaks if s>=3)}")

    print(f"\n  {'─'*55}")
    print(f"  MONTHLY BREAKDOWN — LAST 3 YEARS")
    print(f"  {'─'*55}")

    monthly = trade_log.groupby("month").size()
    recent = monthly[monthly.index >= pd.Period("2023-01", "M")]
    print(f"\n  {'Month':<12}{'Trades':>8}{'Trades/wk':>12}")
    print(f"  {'─'*35}")
    for month, cnt in recent.items():
        wk = cnt / 4.33
        flag = " ← zero weeks likely" if cnt < 3 else ""
        print(f"  {str(month):<12}{cnt:>8}{wk:>12.1f}{flag}")

    print(f"\n  {'─'*55}")
    print(f"  HONEST EXPECTATION")
    print(f"  {'─'*55}")
    print(f"""
  The 3.5 trades/week is a 22-year mean that includes
  very active macro periods (2008, 2015, 2022).

  In quiet macro regimes (stable Fed/ECB, low divergence):
    - Zero-trade weeks are common and expected
    - 1-2 trade weeks are the norm
    - 0 trades in the first 2 weeks is NOT unusual

  The model is waiting for genuine macro dislocations.
  When the next Fed/ECB surprise hits, expect a cluster
  of signals — possibly 5-10 in a single week.

  Weeks to wait before investigating low frequency:
    If < 2 trades per week after 8 weeks → run
    live_vs_backtest_zscore_v1.py to diagnose.
""")

if __name__ == "__main__":
    main()
