#!/usr/bin/env python3
"""Monitor agent cycles after Apify recovery.

Prints a report of recent cycles, focusing on post-fix performance.
Run manually anytime to check status.
"""

import sqlite3
import sys
from pathlib import Path

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

DB_PATH = str(Path(__file__).resolve().parent.parent / "data" / "catalog.db")


def main() -> None:
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row

    # Last Apify-working cycle was #266 at 2026-07-04T10:00
    # Fixes deployed at cycle ~288 (2026-07-06)
    # Find first productive cycle after fixes
    rows = conn.execute("""
        SELECT id, started_at, groups_scanned, groups_failed, posts_fetched,
               posts_analyzed, queries_found, leads_written,
               leads_matched, leads_review, leads_no_match, duplicates, errors
        FROM cycle_log
        ORDER BY id DESC
        LIMIT 20
    """).fetchall()

    print("=" * 100)
    print("  RECENT CYCLES (last 20)")
    print("=" * 100)

    last_productive = None
    post_fix_productive = []

    for r in reversed(rows):
        productive = r["posts_fetched"] > 0
        marker = ""
        if productive and r["id"] > 288:
            marker = " ← POST-FIX"
            post_fix_productive.append(r)
        if productive:
            last_productive = r

        status = "✓" if productive else "✗ 403"
        print(f"  #{r['id']:3d} {r['started_at'][:16]} {status:6s}  "
              f"groups={r['groups_scanned']}/{r['groups_scanned']+r['groups_failed']}  "
              f"posts={r['posts_fetched']:3d}  analyzed={r['posts_analyzed']:3d}  "
              f"queries={r['queries_found']:2d}  "
              f"leads=67:{r['leads_matched']} 68:{r['leads_review']} 69:{r['leads_no_match']}  "
              f"dupes={r['duplicates']:2d}{marker}")

    # Comparison stats
    print()
    print("=" * 100)
    print("  COMPARISON")
    print("=" * 100)

    # Pre-fix period: cycles 203-266 (live, before Apify died)
    pre_fix = conn.execute("""
        SELECT COUNT(*) as cycles,
               SUM(posts_fetched) as posts, SUM(queries_found) as queries,
               SUM(leads_matched) as l67, SUM(leads_review) as l68, SUM(leads_no_match) as l69
        FROM cycle_log
        WHERE id BETWEEN 203 AND 266
    """).fetchone()

    print(f"  PRE-FIX  (cycles 203-266, {pre_fix['cycles']} cycles):")
    print(f"    Posts={pre_fix['posts']}  Queries={pre_fix['queries']}  "
          f"67={pre_fix['l67']}  68={pre_fix['l68']}  69={pre_fix['l69']}")
    if pre_fix["cycles"] > 0:
        print(f"    Per cycle avg: queries={pre_fix['queries']/pre_fix['cycles']:.1f}  "
              f"leads={(pre_fix['l67']+pre_fix['l68']+pre_fix['l69'])/pre_fix['cycles']:.2f}")

    # Post-fix productive cycles
    if post_fix_productive:
        total_67 = sum(r["leads_matched"] for r in post_fix_productive)
        total_68 = sum(r["leads_review"] for r in post_fix_productive)
        total_69 = sum(r["leads_no_match"] for r in post_fix_productive)
        total_queries = sum(r["queries_found"] for r in post_fix_productive)
        total_posts = sum(r["posts_fetched"] for r in post_fix_productive)
        n = len(post_fix_productive)

        print(f"\n  POST-FIX ({n} productive cycles):")
        print(f"    Posts={total_posts}  Queries={total_queries}  "
              f"67={total_67}  68={total_68}  69={total_69}")
        if n > 0:
            print(f"    Per cycle avg: queries={total_queries/n:.1f}  "
                  f"leads={(total_67+total_68+total_69)/n:.2f}")

        if total_67 > 0:
            print(f"\n  ★ LEADY 67 SIĘ POJAWIŁY! {total_67} dopasowanych leadów.")
        elif total_queries > 0:
            print(f"\n  ⚠ Zapytania są ({total_queries}), ale 67 jeszcze nie — za mała próbka lub same nowe zapytania.")
        else:
            print(f"\n  ⚠ Brak zapytań — za wcześnie na ocenę.")
    else:
        print("\n  ⚠ Brak produktywnych cykli po naprawach — Apify prawdopodobnie nadal 403.")
        if last_productive:
            print(f"    Ostatni produktywny cykl: #{last_productive['id']} {last_productive['started_at'][:16]}")

    # Billing status
    bal = conn.execute("""
        SELECT balance_after FROM billing_log
        WHERE mode='live' AND result='charged'
        ORDER BY id DESC LIMIT 1
    """).fetchone()
    if bal:
        print(f"\n  Aktualne saldo Denisa: {bal['balance_after']} tokenów")

    conn.close()


if __name__ == "__main__":
    main()
