#!/usr/bin/env python3
"""Show group ranking with discovery funnel state diagnostics."""

from __future__ import annotations

import sys
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()
    gm = GroupManager(settings.db_path)
    groups = gm.ranking()

    print(
        f"{'State':<10s} {'Grupa':<50s} {'Scans':>5s} "
        f"{'InWin':>5s} {'Hits':>5s} {'QRY':>5s} "
        f"{'HitRate':>8s} {'Last hit':<20s}"
    )
    print("─" * 120)

    for g in groups:
        last_hit = (g["last_hit_at"] or "—")[:19]
        hr = f"{g['hit_rate']:.2f}" if g["scans_in_window"] else "—"
        print(
            f"{g['group_state']:<10s} "
            f"{g['nazwa'][:49]:<50s} "
            f"{g['scans_count']:>5d} "
            f"{g['scans_in_window']:>5d} "
            f"{g['hits_count']:>5d} "
            f"{g['queries_count']:>5d} "
            f"{hr:>8s} "
            f"{last_hit:<20s}"
        )

    print()
    stats = gm.stats()
    by_state = stats.get("by_state", {})
    print(
        f"Total: {stats['total']} | "
        f"Funnel: proven={by_state.get('proven', 0)} "
        f"untested={by_state.get('untested', 0)} "
        f"dead={by_state.get('dead', 0)}"
    )
    gm.close()


if __name__ == "__main__":
    main()
