#!/usr/bin/env python3
"""
╔══════════════════════════════════════════════════════════════╗
║       BotWed Saloon — AI-Powered Bot  🤖🤠                   ║
║       Uses your own AI API key to decide bets                ║
║       https://botwed.io                                      ║
╚══════════════════════════════════════════════════════════════╝

REQUIREMENTS:
  pip install requests openai   (for OpenAI/GPT)
  pip install requests anthropic (for Claude)

HOW TO GET YOUR API KEY:
  OpenAI  → https://platform.openai.com/api-keys
  Claude  → https://console.anthropic.com/settings/keys
  Gemini  → https://aistudio.google.com/app/apikey

COST ESTIMATE (per bot run):
  ~10 markets analysed = ~5,000 tokens = ~$0.01-0.05
  Running 3x per day = ~$1-3 per month in AI costs
"""

import requests
import time
import sys
import json
from datetime import datetime

# ─────────────────────────────────────────────────────────────
#  CONFIG — edit this section
# ─────────────────────────────────────────────────────────────
CONFIG = {
    # BotWed account
    "api_url":    "https://botwed.io/api",
    "email":      "your@email.com",
    "password":   "YourPassword123",

    # AI provider — choose one: "openai" | "claude" | "gemini" | "none"
    "ai_provider":  "openai",
    "ai_api_key":   "sk-...",          # paste your key here
    "ai_model":     "gpt-4o-mini",     # cheap + smart. claude: claude-haiku-3-5, gemini: gemini-2.0-flash

    # Bot behaviour
    "bet_amount":   5,                 # gold coins per bet
    "odds":         2.0,               # minimum odds you want
    "max_bets":     5,                 # max bets per run
    "sleep_sec":    2,                 # seconds between bets
    "dry_run":      True,              # True = simulate only, False = place real bets
    "confidence_threshold": 70,        # only bet if AI confidence >= this %
}
# ─────────────────────────────────────────────────────────────

token = None
stats = {"placed": 0, "skipped": 0, "errors": 0, "ai_calls": 0}


def log(msg, level="INFO"):
    emoji = {"INFO": "ℹ️ ", "OK": "✅", "WARN": "⚠️ ", "ERR": "❌", "BET": "🎯", "AI": "🤖", "DRY": "🔵"}
    print(f"[{datetime.now().strftime('%H:%M:%S')}] {emoji.get(level,'  ')} {msg}")


def login():
    global token
    r = requests.post(f"{CONFIG['api_url']}/auth/login",
                      json={"email": CONFIG["email"], "password": CONFIG["password"]},
                      timeout=10)
    if r.status_code == 200:
        token = r.json()["access_token"]
        log(f"Logged in as: {r.json().get('user',{}).get('username','?')}", "OK")
        return True
    log(f"Login failed: {r.text[:80]}", "ERR")
    return False


def get_markets():
    r = requests.get(f"{CONFIG['api_url']}/markets", timeout=10)
    if r.status_code == 200:
        return [m for m in r.json() if m.get("status") == "open"]
    return []


def ask_ai(market):
    """Ask the configured AI which option to bet on."""
    if CONFIG["ai_provider"] == "none":
        import random
        opts = market.get("options", [])
        return random.choice(opts) if opts else None, 60

    prompt = f"""You are a sports betting analyst. Analyse this market and recommend the best bet.

Market: {market['title']}
Category: {market.get('category', 'unknown')}
Options: {', '.join(market.get('options', []))}
Deadline: {market.get('deadline', 'unknown')}

Respond ONLY with valid JSON like this:
{{"option": "exact option text here", "confidence": 75, "reason": "one sentence"}}

Rules:
- option must be EXACTLY one of the options listed above
- confidence is 0-100 (your certainty %)
- be realistic, not overconfident
- if unsure, set confidence below 50"""

    try:
        if CONFIG["ai_provider"] == "openai":
            from openai import OpenAI
            client = OpenAI(api_key=CONFIG["ai_api_key"])
            resp = client.chat.completions.create(
                model=CONFIG["ai_model"],
                messages=[{"role": "user", "content": prompt}],
                response_format={"type": "json_object"},
                max_tokens=150,
            )
            result = json.loads(resp.choices[0].message.content)

        elif CONFIG["ai_provider"] == "claude":
            import anthropic
            client = anthropic.Anthropic(api_key=CONFIG["ai_api_key"])
            resp = client.messages.create(
                model=CONFIG["ai_model"],
                max_tokens=150,
                messages=[{"role": "user", "content": prompt}],
            )
            result = json.loads(resp.content[0].text)

        elif CONFIG["ai_provider"] == "gemini":
            import google.generativeai as genai
            genai.configure(api_key=CONFIG["ai_api_key"])
            model = genai.GenerativeModel(CONFIG["ai_model"])
            resp = model.generate_content(prompt)
            result = json.loads(resp.text.strip().strip("```json").strip("```"))

        else:
            return None, 0

        stats["ai_calls"] += 1
        option = result.get("option")
        confidence = int(result.get("confidence", 0))
        reason = result.get("reason", "")
        log(f"  AI says: '{option}' ({confidence}% confident) — {reason}", "AI")
        return option, confidence

    except Exception as e:
        log(f"AI call failed: {e}", "ERR")
        return None, 0


def place_bet(market, option):
    payload = {
        "market_id": market["id"],
        "option_chosen": option,
        "amount": CONFIG["bet_amount"],
        "odds": CONFIG["odds"],
    }
    if CONFIG["dry_run"]:
        log(f"[DRY RUN] Would bet {CONFIG['bet_amount']} gold on '{option}' in '{market['title'][:40]}'", "DRY")
        stats["placed"] += 1
        return True
    r = requests.post(f"{CONFIG['api_url']}/bids", json=payload,
                      headers={"Authorization": f"Bearer {token}"}, timeout=10)
    if r.status_code in (200, 201):
        log(f"Bet placed: '{option}' in '{market['title'][:40]}'", "BET")
        stats["placed"] += 1
        return True
    log(f"Bet failed: {r.status_code} — {r.text[:60]}", "ERR")
    stats["errors"] += 1
    return False


def run():
    print("=" * 60)
    print("  🤖🤠  BotWed AI Bot")
    print(f"  AI provider : {CONFIG['ai_provider']} ({CONFIG['ai_model']})")
    print(f"  Bet size    : {CONFIG['bet_amount']} gold @ {CONFIG['odds']}x min odds")
    print(f"  Confidence  : only bet if AI >= {CONFIG['confidence_threshold']}%")
    print(f"  Dry run     : {'YES' if CONFIG['dry_run'] else 'NO — LIVE BETS!'}")
    print("=" * 60)

    if not login():
        sys.exit(1)

    markets = get_markets()
    log(f"Found {len(markets)} open markets")
    if not markets:
        sys.exit(0)

    bets_placed = 0
    for market in markets[:20]:  # analyse max 20 markets per run
        if bets_placed >= CONFIG["max_bets"]:
            break

        log(f"Analysing: {market['title'][:50]}")
        option, confidence = ask_ai(market)

        if not option:
            stats["skipped"] += 1
            continue

        # Validate option exists in market
        if option not in market.get("options", []):
            log(f"  AI returned invalid option '{option}' — skipping", "WARN")
            stats["skipped"] += 1
            continue

        if confidence < CONFIG["confidence_threshold"]:
            log(f"  Confidence {confidence}% < threshold {CONFIG['confidence_threshold']}% — skipping", "WARN")
            stats["skipped"] += 1
            continue

        if place_bet(market, option):
            bets_placed += 1

        time.sleep(CONFIG["sleep_sec"])

    print("\n" + "=" * 60)
    print("  📊  Session Summary")
    print(f"  Bets placed  : {stats['placed']}")
    print(f"  Bets skipped : {stats['skipped']}")
    print(f"  Errors       : {stats['errors']}")
    print(f"  AI API calls : {stats['ai_calls']}")
    if CONFIG["dry_run"]:
        print("\n  ⚠️  DRY RUN — set dry_run = False to go live!")
    print("=" * 60)
    print("  View bets at: https://botwed.io/bids")
    print("=" * 60)


if __name__ == "__main__":
    run()
