#!/usr/bin/env python3
"""Report required custom-field schema health by GHL location."""

import argparse

from common import SchemaResolver, select_accounts

CONTACT_FIELDS = [
    "sucursal",
    "tienda",
    "canal_origen",
    "fuente_prospecto",
    "marca_vehiculo",
    "version_vehiculo",
    "ano_vehiculo",
]

OPPORTUNITY_FIELDS = [
    "sucursal",
    "tienda",
    "canal_origen",
    "fuente_prospecto",
    "vehiculo",
]


def print_section(title, resolved, missing, show_ids):
    status = "OK" if not missing else "FALTAN"
    print(f"  {title}: {status}")
    if show_ids:
        for field_name, field_id in resolved.items():
            print(f"    OK {field_name}: {field_id}")
    elif resolved:
        print(f"    OK: {', '.join(resolved)}")
    if missing:
        print(f"    Faltantes: {', '.join(missing)}")


def main():
    parser = argparse.ArgumentParser(description="Reporte de salud de campos personalizados por sucursal.")
    parser.add_argument("--location", help="Location ID especifica")
    parser.add_argument("--all", action="store_true", help="Procesa todas las sucursales")
    parser.add_argument("--include-main", action="store_true", help="Incluye la cuenta principal")
    parser.add_argument("--show-ids", action="store_true", help="Muestra IDs dinamicos resueltos")
    args = parser.parse_args()

    accounts = select_accounts(args.location, args.all, args.include_main)
    resolver = SchemaResolver()
    locations_ok = 0
    locations_with_missing = 0

    print("=== REPORTE DE SALUD DE CUSTOM FIELDS MP ===")
    print(f"Locations evaluadas: {len(accounts)}")
    print("Regla: cada schema se resuelve con /objects/ y luego /objects/{objectKey}.\n")

    for account in accounts:
        location_id = account["location_id"]
        token = account["token"]
        name = account.get("nombre") or location_id
        print(f"{name} ({location_id})")

        contact_resolved, contact_missing = resolver.resolve_required(token, location_id, "contact", CONTACT_FIELDS)
        opp_resolved, opp_missing = resolver.resolve_required(token, location_id, "opportunity", OPPORTUNITY_FIELDS)

        print_section("Contactos", contact_resolved, contact_missing, args.show_ids)
        print_section("Oportunidades", opp_resolved, opp_missing, args.show_ids)

        if contact_missing or opp_missing:
            locations_with_missing += 1
        else:
            locations_ok += 1
        print("-" * 90)

    print("RESUMEN")
    print(f"  Locations OK: {locations_ok}")
    print(f"  Locations con faltantes: {locations_with_missing}")


if __name__ == "__main__":
    main()
