from datetime import datetime, timezone
from pathlib import Path

from .db import get_conn

LEARNINGS_PATH = Path.home() / ".betlab" / "LEARNINGS.md"


def _already_logged(bet_id: int) -> bool:
    if not LEARNINGS_PATH.exists():
        return False
    return f"#{bet_id}" in LEARNINGS_PATH.read_text()


def _generate_lesson(bet: dict) -> str:
    status = bet["status"]
    notes = (bet.get("notes") or "").lower()
    pnl = (bet["payout"] or 0) - bet["stake"]
    sign = f"+{pnl:.1f}" if pnl >= 0 else f"{pnl:.1f}"
    header = f"#{bet['id']} {bet['game_date']} | {bet['selection']} @ {bet['odds_taken']:.2f} | {status.upper()} {sign} RON"

    if status == "won":
        if "stale" in notes:
            lesson = "Stale line timing worked. Replicate: check Pinnacle gap before placing."
        elif "simmons" in notes or "lowe" in notes or "podcast" in notes:
            lesson = "Podcast signal aligned with result. Note source reliability."
        else:
            lesson = f"Won. Notes: {bet['notes'] or 'none'}."
    elif status == "lost":
        if "stale" in notes:
            lesson = "Stale line bet lost. Verify vig math — line gap doesn't always survive vig."
        elif "injury" in notes or "questionable" in notes or "knee" in notes:
            lesson = "Injury-driven bet lost. Good process (killed Tatum, took total) but result went wrong. Variance."
        elif "tatum" in notes:
            lesson = "Injury news play failed. Check if line moved enough before placing."
        else:
            lesson = f"Lost. Notes: {bet['notes'] or 'none — add notes when logging'}."
    elif status == "push":
        lesson = "Pushed exactly on line. No edge info, no lesson."
    else:
        lesson = "Voided. Likely player DNP or data mismatch."

    return f"- {header}\n  {lesson}"


def run_learn(since: str | None = None) -> int:
    """Generate lessons for unseen settled bets. Returns count of new lessons written."""
    q = "SELECT * FROM bets WHERE status IN ('won','lost','push','void') ORDER BY game_date, id"
    params: list = []
    if since:
        q = q.replace("WHERE", "WHERE game_date >= ? AND")
        params.insert(0, since)

    with get_conn() as conn:
        bets = [dict(r) for r in conn.execute(q, params).fetchall()]

    new_bets = [b for b in bets if not _already_logged(b["id"])]
    if not new_bets:
        return 0

    lines = []
    if not LEARNINGS_PATH.exists():
        lines.append("# betlab — learnings\n")
        lines.append("One lesson per settled bet. Auto-generated by `betlab learn`.\n")

    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    lines.append(f"\n## {today}\n")
    for bet in new_bets:
        lines.append(_generate_lesson(bet))

    with open(LEARNINGS_PATH, "a") as f:
        f.write("\n".join(lines) + "\n")

    return len(new_bets)
