#!/usr/bin/env python3
"""CLI: Fetch offers from eBay + Allegro and rebuild the local catalog index.

Prints a report: total indexed, OE coverage, brand/model coverage, top categories.
"""

import json
import logging
import sqlite3
import sys
from collections import Counter
from pathlib import Path

from agent_samochodowy.config import Settings
from agent_samochodowy.matcher.catalog import fetch_allegro_offers, fetch_ebay_offers
from agent_samochodowy.matcher.index import CatalogIndex
from agent_samochodowy.models import Offer

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)


def _print_report(offers: list[Offer]) -> None:
    """Print a summary report of the fetched offers."""
    total = len(offers)
    if total == 0:
        print("\nNo offers to report.")
        return

    has_oe = sum(1 for o in offers if o.oe_numbers)
    has_brand = sum(1 for o in offers if o.brand)
    has_model = sum(1 for o in offers if o.model)
    has_category = sum(1 for o in offers if o.category)
    has_engine = sum(1 for o in offers if o.engine_code)
    has_price = sum(1 for o in offers if o.price is not None)
    not_part = sum(1 for o in offers if not o.is_part)

    currencies: Counter[str] = Counter()
    brands: Counter[str] = Counter()
    categories: Counter[str] = Counter()

    for o in offers:
        if o.price is not None:
            currencies[o.currency] += 1
        if o.brand:
            brands[o.brand] += 1
        if o.category:
            categories[o.category] += 1

    print("\n" + "=" * 60)
    print("RAPORT KATALOGU")
    print("=" * 60)
    print(f"Łącznie ofert:           {total}")
    print(f"Z ceną:                  {has_price} ({has_price * 100 // total}%)")
    print(f"Waluty:                  {dict(currencies)}")
    print(f"Z numerami OE:           {has_oe} ({has_oe * 100 // total}%)")
    print(f"Z rozpoznaną marką:      {has_brand} ({has_brand * 100 // total}%)")
    print(f"Z rozpoznanym modelem:   {has_model} ({has_model * 100 // total}%)")
    print(f"Z kategorią:             {has_category} ({has_category * 100 // total}%)")
    print(f"Z kodem silnika:         {has_engine} ({has_engine * 100 // total}%)")
    print(f"is_part=false:           {not_part}")

    print("\nTOP 10 marek:")
    for brand, count in brands.most_common(10):
        print(f"  {brand:20s} {count:5d} ({count * 100 // total}%)")

    print("\nTOP 10 kategorii:")
    for cat, count in categories.most_common(10):
        print(f"  {cat:20s} {count:5d} ({count * 100 // total}%)")

    print("\n10 przykładowych rekordów Offer:")
    import random
    sample = random.sample(offers, min(10, len(offers)))
    for i, o in enumerate(sample, 1):
        print(f"\n  [{i}] {o.title[:80]}")
        print(f"      brand={o.brand}  model={o.model}  category={o.category}")
        print(f"      oe_numbers={o.oe_numbers[:3]}{'...' if len(o.oe_numbers) > 3 else ''}")
        print(f"      price={o.price} {o.currency}  qty={o.qty}  platform={o.platform}")

    print("=" * 60)


def main() -> None:
    settings = Settings()

    # Ensure data dir exists
    Path(settings.db_path).parent.mkdir(parents=True, exist_ok=True)

    index = CatalogIndex(settings.db_path)

    logger.info("Fetching Allegro offers...")
    allegro = fetch_allegro_offers(settings)
    logger.info("Fetching eBay offers...")
    ebay = fetch_ebay_offers(settings)

    all_offers = allegro + ebay
    logger.info(
        "Total offers fetched: %d (Allegro: %d, eBay: %d)",
        len(all_offers), len(allegro), len(ebay),
    )

    index.build_from_offers(all_offers)
    logger.info("Index built. Total parts indexed: %d", index.count())
    index.close()

    _print_report(all_offers)


if __name__ == "__main__":
    sys.exit(main() or 0)
