"""
FULL STRATEGY OVERHAUL v2 — Full 15-minute window, volume-focused, no arbitrary limits.
Goal: 50+ consistent profitable trades.

Philosophy:
  - Trade the full 15-min window with phase-aware scoring
  - Require 2+ confirming signals (not just MOM)
  - Many smaller positions instead of few large ones
  - Track everything by phase (early/mid/late) and signal combo
"""

path = r"C:\kalshibot\Automated\paper_trade.py"
with open(path, "r", encoding="utf-8") as f:
    content = f.read()

changes = []

# ── 1. Constants overhaul ──────────────────────────────────────────────────────

content = content.replace(
    "MAX_POSITIONS         = 3    # quality over quantity — fewer but better simultaneous positions across markets",
    "MAX_POSITIONS         = 20   # no position cap — let opportunities dictate"
)
content = content.replace(
    "ENTRY_COOLDOWN        = 20    # 20s between entries",
    "ENTRY_COOLDOWN        = 5     # 5s cooldown — trade opportunities aggressively"
)
content = content.replace(
    "SCORE_HIGH             = 25    # score >= 25 \u2192 HIGH confidence",
    "SCORE_HIGH             = 22    # score >= 22 \u2192 HIGH confidence"
)
content = content.replace(
    "SCORE_MEDIUM           = 20    # score >= 20 \u2192 MEDIUM (raised \u2014 weak plays lose money)",
    "SCORE_MEDIUM           = 12    # score >= 12 \u2192 MEDIUM \u2014 lower bar, build data fast"
)
changes.append("Constants: MAX_POSITIONS=20, COOLDOWN=5s, SCORE thresholds lowered")

# ── 2. score_expiration_value: open to full 15-min window ──────────────────────

old_sniper = "    if mins_left > 3.0: return 0, None  # SNIPER MODE: only final 3 minutes \u2014 highest edge window"
new_sniper = (
    "    if mins_left > 15.0: return 0, None  # Full 15-min window \u2014 EXP active all window\n"
    "    # Time confidence: early entries have more BTC-move risk, so score them lower\n"
    "    if   mins_left > 8.0: time_conf = 0.55  # early (8-15 min): BTC has lots of time to cross\n"
    "    elif mins_left > 4.0: time_conf = 0.80  # mid (4-8 min): good setup window\n"
    "    elif mins_left > 2.0: time_conf = 0.95  # near (2-4 min): high confidence\n"
    "    else:                 time_conf = 1.00  # final 2 min: maximum confidence"
)
if old_sniper in content:
    content = content.replace(old_sniper, new_sniper)
    changes.append("EXP: opened to full 15-min window with time_confidence multiplier")
else:
    changes.append("WARNING: SNIPER MODE line not found")

# Also apply time_conf to the score calculation
old_score_calc = "    score = int(min(50, mispricing * 500))  # 500 multiplier: 2%\u219210pts, 6%\u219230pts(HIGH)"
new_score_calc = "    score = int(min(50, mispricing * 500 * time_conf))  # multiplier adjusted by time confidence"
if old_score_calc in content:
    content = content.replace(old_score_calc, new_score_calc)
    changes.append("EXP: score now scaled by time_confidence")
else:
    changes.append("WARNING: score calc line not found")

# ── 3. get_confidence_score: 2-signal requirement ──────────────────────────────

old_signal_rule = (
    "    # Block EXP+LAG with no momentum \u2014 data shows 0W/4L, -$8.12. Never trade this combo alone.\n"
    "    if exp_score > 0 and lag_score > 0 and mom_score == 0:\n"
    '        return 0, None, None, ""\n'
    "    # MOM required on most trades \u2014 proven by data (EXP+MOM=83% WR, EXP+LAG+MOM=100% WR).\n"
    "    # SNIPER EXCEPTION: allow EXP-only trade in final 90s when signal is extreme.\n"
    "    # <90s left + EXP score 40+ = near-certain outcome, momentum irrelevant.\n"
    "    if mom_score == 0:\n"
    '        secs_remaining = market.get("secs_left", 999) if market else 999\n'
    "        if exp_score >= 40 and secs_remaining < 90:\n"
    "            pass  # SNIPER: final-90s EXP override\n"
    "        else:\n"
    '            return 0, None, None, ""'
)
new_signal_rule = (
    "    # Rule: require at least 2 confirming signals\n"
    "    # Data proven: EXP+MOM=83% WR, EXP+LAG+MOM=100% WR\n"
    "    # Keeping EXP+LAG blocked (data: 0W/4L) — needs MOM to confirm\n"
    "    # LAG+MOM (new territory): allowed — both signals needed, track results\n"
    "    # MOM-alone blocked: proven 39% WR loser\n"
    "    # LAG-alone blocked: insufficient evidence\n"
    "    # EXP-alone: only allowed in final 90s with extreme score (sniper)\n"
    "    active_signals = sum([exp_score > 0, lag_score > 0, mom_score > 0])\n"
    "    secs_remaining = market.get(\"secs_left\", 999) if market else 999\n"
    "    if active_signals == 1:\n"
    "        # Single signal: only allow EXP-only sniper in final 90s\n"
    "        if exp_score >= 40 and secs_remaining < 90:\n"
    "            pass  # SNIPER: extreme EXP near expiry, go for it\n"
    "        else:\n"
    '            return 0, None, None, ""\n'
    "    elif active_signals >= 2:\n"
    "        # Block EXP+LAG without MOM — data: 0W/4L. Hard no.\n"
    "        if exp_score > 0 and lag_score > 0 and mom_score == 0:\n"
    '            return 0, None, None, ""'
)
if old_signal_rule in content:
    content = content.replace(old_signal_rule, new_signal_rule)
    changes.append("Scoring: 2-signal requirement, LAG+MOM now allowed, smarter logic")
else:
    changes.append("WARNING: signal rule block not found")

# ── 4. Bet sizing: smaller bets for more positions ─────────────────────────────

old_bet = (
    "    if score < SCORE_MEDIUM: return 0.0\n"
    "    # Practical score range: EXP(0-50)+LAG(0-30)+MOM(0-20)=max 100\n"
    "    # Size aggressively on HIGH conviction, conservatively on MEDIUM.\n"
    "    if   score >= 55: pct = 0.14   # very strong:  14% = ~$70 on $500\n"
    "    elif score >= 45: pct = 0.10   # strong HIGH:  10% = ~$50\n"
    "    elif score >= 35: pct = 0.07   # solid HIGH:    7% = ~$35\n"
    "    elif score >= 25: pct = 0.04   # low HIGH:      4% = ~$20\n"
    "    else:             pct = 0.02   # MEDIUM:        2% = ~$10\n"
    "    bet = round(current_balance * pct, 2)\n"
    "    bet = max(1.00, min(bet, current_balance * 0.18))  # floor $1, cap 18%\n"
    "    return bet"
)
new_bet = (
    "    if score < SCORE_MEDIUM: return 0.0\n"
    "    # Many-position strategy: smaller individual bets, more opportunities\n"
    "    # Score range: EXP(0-50)+LAG(0-30)+MOM(0-20)=max 100\n"
    "    if   score >= 55: pct = 0.06   # very strong: 6% = ~$30 on $500\n"
    "    elif score >= 40: pct = 0.04   # strong:      4% = ~$20\n"
    "    elif score >= 25: pct = 0.025  # HIGH:      2.5% = ~$12\n"
    "    elif score >= 18: pct = 0.015  # MED-HIGH:  1.5% = ~$7\n"
    "    else:             pct = 0.010  # MEDIUM:      1% = ~$5\n"
    "    bet = round(current_balance * pct, 2)\n"
    "    bet = max(1.00, min(bet, current_balance * 0.10))  # floor $1, cap 10% per trade\n"
    "    return bet"
)
if old_bet in content:
    content = content.replace(old_bet, new_bet)
    changes.append("Bet sizing: smaller per-trade (1-6%) to allow more simultaneous positions")
else:
    changes.append("WARNING: bet sizing block not found")

# ── 5. Add phase tracking to log_analytics ─────────────────────────────────────

old_analytics_record = '        "secs_left"        : pos.get("secs_left", 0),'
new_analytics_record = (
    '        "secs_left"        : pos.get("secs_left", 0),\n'
    '        "phase"            : ("late" if pos.get("secs_left",999) < 120\n'
    '                              else "mid" if pos.get("secs_left",999) < 360\n'
    '                              else "early"),  # early=6-15min mid=2-6min late=<2min'
)
if old_analytics_record in content:
    content = content.replace(old_analytics_record, new_analytics_record)
    changes.append("Analytics: added phase tracking (early/mid/late) to every trade")
else:
    changes.append("WARNING: analytics secs_left line not found")

# ── 6. PROFIT_TARGET + STOP_LOSS: phase-aware via paper_enter ──────────────────
# Adjust profit target based on time: early window gets 30% (less certain), late gets 40%
old_target_calc = "    target   = min(round(entry_price * (1 + PROFIT_TARGET), 4), 0.92)"
new_target_calc = (
    "    # Phase-aware profit target: early trades get lower target (more uncertainty)\n"
    "    secs_left_at_entry = market.get(\"secs_left\", 300)\n"
    "    if   secs_left_at_entry > 480: phase_target = 0.28  # early: 28%, quick flip\n"
    "    elif secs_left_at_entry > 240: phase_target = 0.33  # mid:   33%\n"
    "    elif secs_left_at_entry > 90:  phase_target = 0.38  # near:  38%\n"
    "    else:                          phase_target = 0.45  # late:  45%, near-certain\n"
    "    target   = min(round(entry_price * (1 + phase_target), 4), 0.97)"
)
if old_target_calc in content:
    content = content.replace(old_target_calc, new_target_calc)
    changes.append("paper_enter: phase-aware profit targets (28% early → 45% late)")
else:
    changes.append("WARNING: target calc line not found")

# Write back
with open(path, "w", encoding="utf-8") as f:
    f.write(content)

print("=== STRATEGY v2 CHANGES ===")
for c in changes:
    status = "OK  " if "WARNING" not in c else "FAIL"
    print(f"  [{status}] {c}")

# Verification
with open(path, "r", encoding="utf-8") as f:
    lines = f.readlines()

print("\n=== VERIFICATION ===")
checks = {
    "MAX_POSITIONS=20":       any("= 20" in l and "MAX_POSITIONS" in l for l in lines),
    "COOLDOWN=5":             any("= 5 " in l and "ENTRY_COOLDOWN" in l for l in lines),
    "SCORE_HIGH=22":          any("= 22" in l and "SCORE_HIGH" in l for l in lines),
    "SCORE_MEDIUM=12":        any("= 12" in l and "SCORE_MEDIUM" in l for l in lines),
    "Full 15min window":      any("15.0" in l and "mins_left" in l for l in lines),
    "time_conf multiplier":   any("time_conf" in l for l in lines),
    "2-signal requirement":   any("active_signals" in l for l in lines),
    "New bet sizing 6%":      any("pct = 0.06" in l for l in lines),
    "Phase tracking":         any("phase" in l and "early" in l for l in lines),
    "Phase-aware targets":    any("phase_target" in l for l in lines),
}
for k, v in checks.items():
    print(f"  {'OK  ' if v else 'FAIL'} {k}")

print(f"\nFile size: {sum(len(l) for l in lines):,} chars, {len(lines)} lines")
