#!/usr/bin/env python3
"""Billing report: revenue vs cost analysis for a date range.

Usage:
    python3 scripts/billing_report.py [--days 7] [--since 2026-06-15]
"""

from __future__ import annotations

import argparse
import sqlite3
import sys
from datetime import datetime, timedelta
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))

from agent_samochodowy.config import Settings


def report(db_path: str, since: str) -> None:
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row

    # --- Revenue (tokens charged / would_charge) ---
    cur = conn.execute("""
        SELECT action_type, result, SUM(tokens) as total_tokens, COUNT(*) as cnt
        FROM billing_log
        WHERE timestamp >= ? AND result IN ('would_charge', 'charged')
        GROUP BY action_type, result
    """, (since,))

    scan_tokens = 0.0
    scan_count = 0
    lead_67_tokens = 0.0
    lead_67_count = 0
    lead_68_tokens = 0.0
    lead_68_count = 0

    for row in cur.fetchall():
        t = row["total_tokens"]
        c = row["cnt"]
        if row["action_type"] == "scan":
            scan_tokens += t
            scan_count += c
        elif row["action_type"] == "lead":
            # Distinguish by token amount
            per_lead = t / c if c else 0
            if per_lead >= 4.0:
                lead_67_tokens += t
                lead_67_count += c
            elif per_lead >= 1.0:
                lead_68_tokens += t
                lead_68_count += c

    total_tokens = scan_tokens + lead_67_tokens + lead_68_tokens

    # --- Mode info ---
    cur = conn.execute("""
        SELECT DISTINCT mode FROM billing_log WHERE timestamp >= ?
    """, (since,))
    modes = [row[0] for row in cur.fetchall()]
    mode_str = "/".join(modes) if modes else "brak danych"

    # --- Cycles ---
    cur = conn.execute("""
        SELECT COUNT(*) as cycles,
               COALESCE(SUM(groups_scanned), 0) as total_scans,
               COALESCE(SUM(leads_matched), 0) as total_67,
               COALESCE(SUM(leads_review), 0) as total_68,
               COALESCE(SUM(leads_no_match), 0) as total_69
        FROM cycle_log
        WHERE started_at >= ?
    """, (since,))
    cl = cur.fetchone()

    conn.close()

    # --- Print ---
    print(f"\n{'='*60}")
    print(f"  BILLING REPORT  od {since}")
    print(f"  Tryb: {mode_str}")
    print(f"{'='*60}")
    print(f"\n  Cykle: {cl['cycles']}")
    print(f"  Grupy skanowane: {cl['total_scans']}")
    print(f"  Leady 67/68/69: {cl['total_67']} / {cl['total_68']} / {cl['total_69']}")

    print(f"\n  --- PRZYCHÓD (tokeny) ---")
    print(f"  Skany:     {scan_count:>4} × 0.5 = {scan_tokens:>8.1f} tokenów")
    print(f"  Leady 67:  {lead_67_count:>4} × 5.0 = {lead_67_tokens:>8.1f} tokenów")
    print(f"  Leady 68:  {lead_68_count:>4} × 2.0 = {lead_68_tokens:>8.1f} tokenów")
    print(f"  RAZEM:     {scan_count + lead_67_count + lead_68_count:>4}       = {total_tokens:>8.1f} tokenów")

    if scan_count > 0:
        cost_per_scan = total_tokens / scan_count if scan_count else 0
        scans_per_67 = scan_count / lead_67_count if lead_67_count else float("inf")
        print(f"\n  --- EFEKTYWNOŚĆ ---")
        print(f"  Skanów na 1 lead 67: {scans_per_67:.0f}")

    if total_tokens == 0:
        print(f"\n  Brak naliczonych tokenów w tym okresie.")

    print(f"\n{'='*60}\n")


def main() -> None:
    parser = argparse.ArgumentParser(description="Billing report")
    parser.add_argument("--days", type=int, default=7)
    parser.add_argument("--since", type=str, default=None)
    args = parser.parse_args()

    settings = Settings()
    since = args.since or (datetime.now() - timedelta(days=args.days)).isoformat()
    report(settings.db_path, since)


if __name__ == "__main__":
    main()
