#!/usr/bin/env python3
"""
Script read-only para verificar allowDuplicateContact y allowDuplicateOpportunity
en GHL para la Marca y sucursales específicas.

Uso:
  python scripts/check_allowDuplicate_settings.py

No hace mutaciones. Solo GET a /locations/{location_id}.
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import json
import requests
from sync_engine import parse_accounts_csv

BASE_URL = "https://services.leadconnectorhq.com"

# location_ids de interés
LOCATIONS_OF_INTEREST = {
    "GbKkBpCmKu2QmloKFHy3": "Marca (Monte Providencia)",
    "jE41bVhhnb5T505BFm4F": "Morelia 1",
    "nF1uEaYB3mCK5em9bPn2": "Eugenia",
    "uZnMH5bO6MXTHcgHeyq9": "Pilares"
}

def check_location_settings(location_id, token, friendly_name):
    """
    GET /locations/{location_id} para obtener settings.
    Retorna: (status_code, name, settings_dict o None, error_msg o None)
    """
    url = f"{BASE_URL}/locations/{location_id}"
    headers = {
        "Authorization": f"Bearer {token}",
        "Version": "2021-07-28",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0"
    }
    
    try:
        response = requests.get(url, headers=headers, timeout=15)
        status = response.status_code
        
        if status == 200:
            data = response.json()
            location_obj = data.get("location", {})
            name = location_obj.get("name", "N/A")
            settings = location_obj.get("settings", {})
            return (status, name, settings, None)
        else:
            error_msg = f"HTTP {status}"
            try:
                error_detail = response.json()
                error_msg += f": {error_detail}"
            except:
                error_msg += f": {response.text[:200]}"
            return (status, None, None, error_msg)
    except Exception as e:
        return (None, None, None, str(e))


def main():
    print("\n" + "="*100)
    print("Verificacion de allowDuplicate Settings en GHL")
    print("="*100)
    
    # Cargar tokens
    try:
        accounts = parse_accounts_csv()
    except Exception as e:
        print(f"ERROR: No se pudo cargar CSV: {e}")
        return 1
    
    # Mapear location_id -> token
    token_map = {acc['location_id']: acc['token'] for acc in accounts}
    
    # Preparar resultados
    results = []
    
    for loc_id, friendly_name in LOCATIONS_OF_INTEREST.items():
        print(f"\n[{friendly_name}] location_id={loc_id}")
        
        if loc_id not in token_map:
            print(f"  [WARN] No se encontro token para esta location en el CSV")
            results.append({
                "location_id": loc_id,
                "name": friendly_name,
                "status": "MISSING_TOKEN",
                "error": "Location no en CSV"
            })
            continue
        
        token = token_map[loc_id]
        status, name, settings, error = check_location_settings(loc_id, token, friendly_name)
        
        if error:
            print(f"  [ERROR] {error}")
            results.append({
                "location_id": loc_id,
                "name": friendly_name,
                "status": status,
                "error": error
            })
        else:
            allow_dup_contact = settings.get("allowDuplicateContact", "N/A")
            allow_dup_opp = settings.get("allowDuplicateOpportunity", "N/A")
            
            print(f"  [OK] HTTP {status}")
            print(f"       Name: {name}")
            print(f"       allowDuplicateContact: {allow_dup_contact}")
            print(f"       allowDuplicateOpportunity: {allow_dup_opp}")
            
            results.append({
                "location_id": loc_id,
                "name": friendly_name,
                "ghl_name": name,
                "status": status,
                "allowDuplicateContact": allow_dup_contact,
                "allowDuplicateOpportunity": allow_dup_opp
            })
    
    # Tabla resumen
    print("\n" + "="*100)
    print("TABLA RESUMEN")
    print("="*100)
    print(f"{'Location ID':<25} {'Account Name':<20} {'HTTP Status':<12} {'allowDupContact':<18} {'allowDupOpp':<18}")
    print("-"*100)
    
    for result in results:
        loc_id = result["location_id"]
        acct_name = result["name"][:19]
        status = str(result.get("status", "ERROR"))
        
        if result.get("status") == 200:
            allow_contact = str(result.get("allowDuplicateContact", "N/A"))
            allow_opp = str(result.get("allowDuplicateOpportunity", "N/A"))
        else:
            allow_contact = "ERROR"
            allow_opp = result.get("error", "ERROR")[:15]
        
        print(f"{loc_id:<25} {acct_name:<20} {status:<12} {allow_contact:<18} {allow_opp:<18}")
    
    print("="*100)
    
    return 0


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