"""
Value Hunter Backtest
=====================
Sadece modelin büroyu yendiği (Pozitif Edge) maçları oynar.
"""

import os, sys, json, time, psycopg2
from psycopg2.extras import RealDictCursor

AI_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(AI_DIR)
sys.path.insert(0, ROOT_DIR)
if "scripts" in os.path.basename(AI_DIR): ROOT_DIR = os.path.dirname(ROOT_DIR)
from services.single_match_orchestrator import get_single_match_orchestrator

def get_clean_dsn() -> str:
    return "postgresql://suggestbet:SuGGesT2026SecuRe@localhost:15432/boilerplate_db"

MATCH_IDS = [
    "v2ljcst50nk37x04xwimpi50", "7gz0bhb5yvdssazl3y5946kno", "7ftj7kbu4rzpewxravf3luuc4",
    "7f1z4e8ch1dm5q677644cky6s", "7ffq3aq3so22iymfdzch63nys", "rrkmeuymz7gzvoz8mplikzdg",
    "7hegc9covicy699bxsi81xkb8", "7gl7rpr1hjayk3e5ut0gr613o", "7g7d86i3738287xfvyfeffcwk",
    "7hs4boe4hv80muawocevvx2j8", "7ijhsloieg4t9yp5cxp0duln8", "7ixaiiptli5ek32kuybuni4gk",
    "7i5sfh41cjpwg4l972dm487x0", "eo7g4wunxxxr8uv45q8p5x638", "7dinds2937w4645wva2rddlas",
    "7b5ukdhvqh62wtndeqfg01ixg", "7bjptsj24gndoydn7n0202g44", "7cqxf3vo58ewrwmoom5xiyexg",
    "7bxjl9h2hnf165rlp3o1vfztg", "7eo8zrez08c342rqsezpvq39w", "7as1muhs98vdarlhsean4bspg",
    "7dwhj8cfxv6v6bzxpu5e3h05w", "7d4vq4417ps84yjzh95bnvvv8", "7ea9z501jgp9kxw3gay4myrkk",
    "7cd3401itlty6ded7c1wct0yc", "ebgpz9mcije2snv986n6587pw", "i7ar1dkhvcwpxmkyks65ib6c",
    "lyek7tyy6qk2xjs9vblucnx0", "hdn9qtyn3ysjwbc3i2trantg", "3y2bnssfqlajosiz2gpkn6xhw",
    "40pehd14s9djjtycujavbex3o", "3xnbfjznzmnwml20akbgnis5w", "2eovi2rcc2l4ha7fpb2w7e1hw",
    "2bwuikdjyyuithhru8ka8o00k", "2d3pcd76ya9ihi9yotxc553is", "1e9it04z4epy2etdxsffe7m6s",
    "7af49jgo4iulv1k8cplj9smj8", "5k3vrz619hdu9nx4rnx6uim1g", "amjppgpetnyr0iisi241kgkyc",
    "coqrhq09kxd16iejvgtzj3mz8", "d8ysan1qdctmkvjaz2adw7aqc", "9ttciz0gtb0z09ev1q5fe0ro4",
    "9u720o37yaddqu1w6hlszpnh0", "7ijezdjp8t0rjti91ac63hyxg", "72gvdvztbb3dn79jidzzxzcb8",
    "6uof1v2s6vrpieeml2bwo9tlg", "91dd8ia3m0bxoqzjgyo3ptsk", "3tj1nt3udsbvb9soqn2cs6gpg",
    "1br5g88o5idtjxka1fr6zg4k4", "akuesquthbmxlzckvnqmgles4"
]

def run_value_hunter():
    print("💎 VALUE HUNTER: SADECE HATALI ORANLARI YAKALA")
    print("="*60)

    dsn = get_clean_dsn()
    conn = psycopg2.connect(dsn)
    cur = conn.cursor(cursor_factory=RealDictCursor)

    placeholders = ','.join(['%s'] * len(MATCH_IDS))
    cur.execute(f"""
        SELECT m.id, m.match_name, m.home_team_id, m.away_team_id,
               m.score_home, m.score_away,
               t1.name as home_team, t2.name as away_team
        FROM matches m
        LEFT JOIN teams t1 ON m.home_team_id = t1.id
        LEFT JOIN teams t2 ON m.away_team_id = t2.id
        WHERE m.id IN ({placeholders}) AND m.status = 'FT'
    """, MATCH_IDS)
    
    rows = cur.fetchall()
    print(f"📊 {len(rows)} maç taranıyor...\n")

    try: orchestrator = get_single_match_orchestrator()
    except Exception as e:
        print(f"❌ AI Hatası: {e}")
        return

    total_bet = 0
    total_won = 0
    total_profit = 0.0
    total_edge_found = 0

    for i, row in enumerate(rows):
        match_id = str(row['id'])
        home = row['home_team'] or "?"
        away = row['away_team'] or "?"
        h_score = row['score_home'] or 0
        a_score = row['score_away'] or 0

        try:
            pred = orchestrator.analyze_match(match_id)
            if not pred: continue

            # Tüm önerileri kontrol et
            picks = pred.get("expert_recommendation", {}).get("value_picks", [])
            if not picks: picks = [pred.get("expert_recommendation", {}).get("main_pick")]
            
            played_this_match = False

            for pick_data in picks:
                if not pick_data: continue
                pick = pick_data.get("pick")
                conf = pick_data.get("confidence", 0)
                odds = pick_data.get("odds", 0)
                edge = pick_data.get("edge", 0)

                # VALUE KURALI: Model bürodan en az %10 daha iyi olmalı
                if edge < 10: continue
                if odds < 1.20: continue

                total_bet += 1
                total_edge_found += edge
                won = False
                pick_clean = str(pick).upper()

                if pick_clean in ["1", "MS 1"] and h_score > a_score: won = True
                elif pick_clean in ["X", "MS X"] and h_score == a_score: won = True
                elif pick_clean in ["2", "MS 2"] and a_score > h_score: won = True
                elif "ÜST" in pick_clean or "OVER" in pick_clean:
                    line = 2.5
                    if "1.5" in pick_clean: line = 1.5
                    if (h_score + a_score) > line: won = True
                elif "ALT" in pick_clean or "UNDER" in pick_clean:
                    line = 2.5
                    if "1.5" in pick_clean: line = 1.5
                    if (h_score + a_score) < line: won = True
                elif "VAR" in pick_clean and h_score > 0 and a_score > 0: won = True
                elif "YOK" in pick_clean and (h_score == 0 or a_score == 0): won = True

                if won:
                    total_won += 1
                    profit = odds - 1.0
                    total_profit += profit
                    print(f"[{i+1}] ✅ {home} vs {away} | {pick} ({edge:.0f}% Edge) -> WON! (+{profit:.2f})")
                else:
                    total_profit -= 1.0
                    print(f"[{i+1}] ❌ {home} vs {away} | {pick} ({edge:.0f}% Edge) -> LOST")
                
                played_this_match = True
                break # Maç başına tek bahis

        except Exception: pass

    print("\n" + "="*60)
    print("💎 VALUE HUNTER SONUÇLARI")
    print("="*60)
    print(f"Toplam Value Bulunan Bahis: {total_bet}")
    print(f"Ortalama Edge: {total_edge_found/total_bet:.1f}%" if total_bet > 0 else "N/A")
    print(f"Kazanılan: {total_won}")
    print(f"Toplam Kâr: {total_profit:.2f} Units")
    
    if total_profit > 0: print("🟢 PARA KAZANDIK!")
    else: print("🔴 PARA KAYBETTİK!")

    cur.close()
    conn.close()

if __name__ == "__main__":
    run_value_hunter()
