"""One-off audit collector for guide candidates. Read-only. Does NOT start the server."""
import json
import sys

from supporthub.app.main import app
from supporthub.app import config
from supporthub.app.db import session_scope
from supporthub.app.models import (
    AddonsProducts, AddonsThreads, AddonsMessages, Tickets,
    ThreadEmbeddings, GeneratedGuide,
)
from supporthub.app.services.embedding_service import embedding_index, EmbeddingService

SCHEMA = "tenant_internal"

out = {"products": [], "existing_guides": [], "thread_dumps": {}, "stats": {}}

with app.app_context():
    from flask import g
    g.tenant_schema = SCHEMA

    # Load the index like startup does
    embedding_index.load_from_db(schema=SCHEMA)
    embedding_index.load_doc_pages_from_db(schema=SCHEMA)
    out["stats"]["index_count"] = embedding_index.count

    svc = EmbeddingService()

    with session_scope(schema=SCHEMA) as session:
        # existing generated guides
        for gg in session.query(GeneratedGuide).all():
            out["existing_guides"].append({
                "id": gg.id, "ticket_id": gg.ticket_id, "suggestion_id": gg.suggestion_id,
                "title": gg.title, "slug": gg.slug,
                "content_len": len(gg.content_md or ""),
                "content_head": (gg.content_md or "")[:1200],
            })

        # products with their provider ids + strong thread counts
        products = session.query(AddonsProducts).all()
        prod_rows = []
        for p in products:
            try:
                provider = int(p.provider_product_id)
            except (ValueError, TypeError):
                continue
            strong = (session.query(ThreadEmbeddings)
                      .filter(ThreadEmbeddings.product_id == provider,
                              ThreadEmbeddings.embedding_quality == 'strong',
                              ThreadEmbeddings.summary_text.isnot(None))
                      .count())
            total = (session.query(ThreadEmbeddings)
                     .filter(ThreadEmbeddings.product_id == provider).count())
            prod_rows.append((p.id, provider, p.name, strong, total))

        # provider map for batch count
        pid_to_provider = {pid: prov for (pid, prov, _, _, _) in prod_rows}

    # batch counts (current default thresholds)
    batch = svc.count_guide_candidates_batch(pid_to_provider, embedding_index)

    # pick products with the most strong threads to audit
    prod_rows.sort(key=lambda r: r[3], reverse=True)
    out["stats"]["total_products"] = len(prod_rows)

    audit_threads = []  # collect thread_ids to dump messages for
    for (pid, provider, name, strong, total) in prod_rows[:6]:
        cands = svc.get_guide_candidates(pid, embedding_index)
        prod_entry = {
            "db_id": pid, "provider_id": provider, "name": name,
            "strong_threads": strong, "total_embeddings": total,
            "batch_candidate_count": batch.get(pid, 0),
            "get_guide_candidates_count": len(cands),
            "candidates": [],
        }
        for c in cands[:12]:
            prod_entry["candidates"].append({
                "thread_id": c["thread_id"], "ticket_id": c["ticket_id"],
                "cluster_size": c["cluster_size"],
                "summary_text": c["summary_text"],
            })
            if c["thread_id"] not in audit_threads and len(audit_threads) < 14:
                audit_threads.append(c["thread_id"])
        out["products"].append(prod_entry)

    # dump full messages for audited threads
    with session_scope(schema=SCHEMA) as session:
        for tid in audit_threads:
            th = session.query(AddonsThreads).filter_by(id=tid).one_or_none()
            if not th:
                continue
            ticket = session.query(Tickets).filter_by(thread_id=tid).one_or_none()
            msgs = sorted(th.messages, key=lambda m: m.created_at)
            out["thread_dumps"][str(tid)] = {
                "subject": th.subject, "product_name": th.product_name,
                "nb_messages": th.nb_messages,
                "ticket_status": ticket.status if ticket else None,
                "messages": [
                    {"dir": m.direction, "author": m.author_display,
                     "body": (m.body_text or "")[:1500]}
                    for m in msgs
                ],
            }

with open("tmp/audit-data.json", "w") as f:
    json.dump(out, f, indent=2, default=str)
print("WROTE tmp/audit-data.json")
print("products audited:", len(out["products"]))
print("existing guides:", len(out["existing_guides"]))
print("thread dumps:", len(out["thread_dumps"]))
for p in out["products"]:
    print(f"  {p['name'][:40]:40} strong={p['strong_threads']:4} batch_cand={p['batch_candidate_count']:4} get_cand={p['get_guide_candidates_count']:4}")
