"""
analyzer.py
Analiza los resultados JSON generados por el extractor.
Versión mínima para debug y pruebas.
"""
import json

def analyze(invoice_json: dict):
    """
    Realiza análisis básico del JSON extraído:
      - cuenta ítems
      - revisa totales y consistencia
      - devuelve un resumen estructurado
    """
    analysis = {
        "summary": {},
        "validations": {},
        "warnings": []
    }

    # 1️⃣ Tipo de factura
    invoice_type = (
        invoice_json.get("invoice_type", {})
        if isinstance(invoice_json.get("invoice_type"), dict)
        else {"verbatim": str(invoice_json.get("invoice_type", ""))}
    )
    analysis["summary"]["invoice_type"] = invoice_type.get("verbatim", "unknown")

    # 2️⃣ Conteo de ítems
    items = invoice_json.get("items", [])
    analysis["summary"]["items_count"] = len(items)

    # 3️⃣ Totales básicos
    totals = invoice_json.get("totals", {})
    gst = totals.get("gst", {}).get("computed") or totals.get("gst", {}).get("verbatim")
    grand_total = totals.get("grand_total", {}).get("computed") or totals.get("grand_total", {}).get("verbatim")
    analysis["summary"]["gst"] = gst
    analysis["summary"]["grand_total"] = grand_total

    # 4️⃣ Validaciones
    validations = totals.get("validations", {}) if isinstance(totals, dict) else {}
    for key in [
        "items_sum_matches_subtotal",
        "subtotal_plus_gst_plus_extras_equals_grand_total",
        "tendered_equals_grand_total",
        "tax_included",
        "gst_rate_present",
        "gst_rate_infered",
        "negative_lines_check"
    ]:
        analysis["validations"][key] = validations.get(key, False)

    # 5️⃣ Estado general
    analysis["summary"]["status"] = invoice_json.get("status", "unknown")

    # 6️⃣ Warnings
    if not items:
        analysis["warnings"].append("No se detectaron ítems en la factura.")
    if not grand_total:
        analysis["warnings"].append("No se encontró el total de la factura.")

    return analysis
