#!/usr/bin/env python3
"""Daily report: aggregated stats from cycle_log + group ranking.

Run manually or via cron (once daily). Reads cycle_log and fb_groups from catalog.db.
"""

from __future__ import annotations

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
from agent_samochodowy.ingestor.groups import GroupManager


def main() -> None:
    settings = Settings()
    conn = sqlite3.connect(settings.db_path)
    conn.row_factory = sqlite3.Row

    today = datetime.now().date()
    yesterday = today - timedelta(days=1)

    # Default: report for last 24h; pass "week" for 7 days
    days = 7 if len(sys.argv) > 1 and sys.argv[1] == "week" else 1
    since = (today - timedelta(days=days)).isoformat()

    cur = conn.execute("""
        SELECT * FROM cycle_log
        WHERE started_at >= ?
        ORDER BY started_at
    """, (since,))
    cycles = [dict(r) for r in cur.fetchall()]

    print("=" * 80)
    print(f"DAILY REPORT — {today.isoformat()} (last {days} day{'s' if days > 1 else ''})")
    print("=" * 80)

    if not cycles:
        print("No cycles recorded in this period.")
        print()
    else:
        # Aggregate
        total_cycles = len(cycles)
        total_posts = sum(c["posts_fetched"] or 0 for c in cycles)
        total_analyzed = sum(c["posts_analyzed"] or 0 for c in cycles)
        total_too_old = sum(c["posts_too_old"] or 0 for c in cycles)
        total_queries = sum(c["queries_found"] or 0 for c in cycles)
        total_leads = sum(c["leads_written"] or 0 for c in cycles)
        total_matched = sum(c["leads_matched"] or 0 for c in cycles)
        total_review = sum(c["leads_review"] or 0 for c in cycles)
        total_no_match = sum(c["leads_no_match"] or 0 for c in cycles)
        total_duplicates = sum(c["duplicates"] or 0 for c in cycles)
        total_errors = sum(c["errors"] or 0 for c in cycles)
        total_groups_scanned = sum(c["groups_scanned"] or 0 for c in cycles)
        total_groups_failed = sum(c["groups_failed"] or 0 for c in cycles)
        halts = [c for c in cycles if c["halted_reason"]]

        buy_pct = f"{total_queries / total_analyzed * 100:.1f}%" if total_analyzed else "—"

        print(f"Cykli:                    {total_cycles}")
        print(f"Grup przeskanowanych:     {total_groups_scanned} (failed: {total_groups_failed})")
        print(f"Postów pobranych:         {total_posts}")
        print(f"  za stare:               {total_too_old}")
        print(f"  analizowanych:          {total_analyzed}")
        print(f"Zapytań kupujących:       {total_queries} ({buy_pct} postów)")
        print(f"Leadów do dgred:          {total_leads}")
        print(f"  67 Dopasowano:          {total_matched}")
        print(f"  68 Do weryfikacji:      {total_review}")
        print(f"  69 Brak dopasowania:    {total_no_match}")
        print(f"Duplikaty autorów:        {total_duplicates}")
        print(f"Błędy:                    {total_errors}")
        if halts:
            print(f"CIRCUIT BREAKER trips:    {len(halts)}")
            for h in halts:
                print(f"  {h['started_at'][:16]}: {h['halted_reason']}")
        print()

        # Per-cycle detail
        print("Per-cycle breakdown:")
        print(f"  {'Czas':<17s} {'Posts':>5s} {'Queries':>7s} {'Leads':>5s} {'67':>3s} {'68':>3s} {'69':>3s} {'Err':>3s} {'Halt'}")
        print("  " + "─" * 65)
        for c in cycles:
            halt_tag = "!!!" if c["halted_reason"] else ""
            print(
                f"  {c['started_at'][:16]:<17s} "
                f"{c['posts_fetched'] or 0:>5d} "
                f"{c['queries_found'] or 0:>7d} "
                f"{c['leads_written'] or 0:>5d} "
                f"{c['leads_matched'] or 0:>3d} "
                f"{c['leads_review'] or 0:>3d} "
                f"{c['leads_no_match'] or 0:>3d} "
                f"{c['errors'] or 0:>3d} "
                f"{halt_tag}"
            )

    conn.close()

    # Group ranking
    print()
    print("=" * 80)
    print("GROUP RANKING (by rolling hit_rate)")
    print("=" * 80)

    gm = GroupManager(settings.db_path)
    groups = gm.ranking()

    print(f"  {'Grupa':<50s} {'Scans':>5s} {'Hits':>4s} {'QRY':>4s} {'Rate':>6s} {'Last hit':<20s}")
    print("  " + "─" * 95)
    for g in groups:
        last_hit = (g["last_hit_at"] or "—")[:16]
        hr = f"{g['hit_rate']:.2f}" if g["scans_count"] else "—"
        print(
            f"  {g['nazwa'][:49]:<50s} "
            f"{g['scans_count']:>5d} "
            f"{g['hits_count']:>4d} "
            f"{g['queries_count']:>4d} "
            f"{hr:>6s} "
            f"{last_hit:<20s}"
        )

    gm.close()
    print()
    print("=" * 80)


if __name__ == "__main__":
    main()
