import os
import sys
import xml.etree.ElementTree as ET
from datetime import datetime

# Setup Django Environment
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
import django
django.setup()

from Models.Empresa import Empresa
from Models.Estado_Empresa import EstadoEmpresa
from Models.Provincia import Provincia
from Models.Localidad import Localidad
from Models.empresa_tipo import EmpresaTipo
from Models.contacto_model import Contacto
from Models.origen import Origen

FILE_PATH = "/home/nicolas/Escritorio/crm_dreinet/Listado_Clientes a 20251212111930AM.xls"
NAMESPACES = {'ss': 'urn:schemas-microsoft-com:office:spreadsheet'}

from django.db.models import Max

def get_or_create_provincia(name):
    if not name or name.lower() == 'none':
        name = "Sin Provincia"
    
    name = name.strip()
    
    provs = Provincia.objects.filter(nombre__iexact=name)
    prov = None
    for p in provs:
        if p.id != 0:
            prov = p
            break
            
    if not prov:
        print(f"Creating Provincia: {name}")
        max_id = Provincia.objects.aggregate(Max('id'))['id__max'] or 0
        new_id = max_id + 1
        prov = Provincia(id=new_id, nombre=name, pais_id=1)
        prov.save()
    return prov

def get_or_create_localidad(name, provincia):
    if not name or name.lower() == 'none':
        name = "Sin Localidad"
        
    name = name.strip()
    
    locs = Localidad.objects.filter(nombre__iexact=name, provincia_id=provincia.id)
    loc = None
    for l in locs:
        if l.id != 0:
            loc = l
            break
            
    if not loc:
        # Manual ID gen to avoid 0/AutoIncrement issues
        max_id = Localidad.objects.aggregate(Max('id'))['id__max'] or 0
        new_id = max_id + 1
        print(f"DEBUG: Creating Localidad '{name}' for Prov {provincia.id}. MaxID={max_id}, NewID={new_id}")
        
        loc = Localidad(
            id=new_id,
            nombre=name, 
            provincia_id=provincia.id, 
            codigo_postal='0000'
        )
        loc.save()
        print(f"DEBUG: Saved Localidad. ID={loc.id}")
        
    else:
        print(f"DEBUG: Found Localidad '{name}' (Prov {provincia.id}). ID={loc.id}")
        
    return loc


def parse_row(cells):
    values = {}
    col_idx = 0
    for cell in cells:
        idx_attr = cell.get('{urn:schemas-microsoft-com:office:spreadsheet}Index')
        if idx_attr:
            col_idx = int(idx_attr) - 1
            
        text_node = cell.find('.//ss:Data', NAMESPACES)
        # Handle case where text_node exists but .text is None (empty tags)
        text = ""
        if text_node is not None:
            if text_node.text:
                text = text_node.text
        
        values[col_idx] = text
        col_idx += 1
    return values


def run():
    print("Starting Import...")
    
    if not os.path.exists(FILE_PATH):
        print("File not found.")
        return

    tree = ET.parse(FILE_PATH)
    root = tree.getroot()
    ws = root.find('.//ss:Worksheet', NAMESPACES)
    table = ws.find('.//ss:Table', NAMESPACES)
    rows = table.findall('.//ss:Row', NAMESPACES)
    
    # IDs for FKs
    estado_activa = EstadoEmpresa.objects.get(pk=1)
    tipo_cliente = EmpresaTipo.objects.get(pk=2)
    # Default Origen: 'Importacion' (Create if not exists)
    origen, _ = Origen.objects.get_or_create(nombre='Importacion Excel', defaults={'created_by': 1})
    
    count_created = 0
    count_updated = 0
    
    # Skip Header (Row 0)
    for i in range(1, len(rows)):
        try:
            row_data = parse_row(rows[i].findall('.//ss:Cell', NAMESPACES))
            
            # Extract fields
            razon_social = row_data.get(0, "").strip() # A
            if not razon_social:
                continue
                
            cuit = row_data.get(20, "").strip() # U
            direccion = row_data.get(4, "").strip() # E
            ciudad_name = row_data.get(5, "").strip() # F
            cp = row_data.get(6, "").strip() # G
            provincia_name = row_data.get(7, "").strip() # H
            email_empresa = row_data.get(31, "").strip() # AF
            
            if cuit == 'None': cuit = None
            if direccion == 'None': direccion = ""
            if cp == 'None': cp = ""
            
            # --- Handle Geo ---
            provincia = get_or_create_provincia(provincia_name)
            localidad = get_or_create_localidad(ciudad_name, provincia)
            
            # --- Create/Update Empresa ---
            # Try finding by CUIT if exists, or Name
            empresa = None
            if cuit:
                empresa = Empresa.objects.filter(cuit=cuit).first()
            
            if not empresa:
                empresa = Empresa.objects.filter(nombre__iexact=razon_social).first()
                
            if empresa:
                print(f"Update existing: {razon_social}")
                empresa.direccion = direccion
                empresa.codigo_postal = cp
                empresa.localidad = localidad
                empresa.provincia = provincia
                empresa.save()
                count_updated += 1
            else:
                print(f"Creating new: {razon_social}")
                try:
                    empresa = Empresa.objects.create(
                        nombre=razon_social,
                        cuit=cuit,
                        estado_empresa=estado_activa,
                        tipo_empresa=tipo_cliente,
                        origen_id=origen.id,
                        provincia=provincia,
                        localidad=localidad,
                        direccion=direccion,
                        codigo_postal=cp,
                        fecha_creacion=django.utils.timezone.now()
                    )
                    count_created += 1
                except Exception as e:
                    import sys
                    sys.stderr.write(f"\nCRASH Creating Empresa: {razon_social}\n")
                    sys.stderr.write(f"Provincia: {provincia.id if provincia else 'None'}\n")
                    sys.stderr.write(f"Localidad: {localidad.id if localidad else 'None'}\n")
                    raise e
                
            # --- Handle Contacts ---
            # Contact 1
            c1_nom = row_data.get(33, "").strip() # AH
            c1_ape = row_data.get(34, "").strip() # AI
            c1_email = row_data.get(35, "").strip() # AJ
            c1_tel = row_data.get(37, "").strip() # AL
            
            if c1_nom and c1_nom != 'None':
                full_name = f"{c1_nom} {c1_ape}".strip()
                # Check duplicate by email?
                if c1_email and c1_email != 'None':
                     if not Contacto.objects.filter(email=c1_email, empresa=empresa).exists():
                         Contacto.objects.create(
                             nombre=full_name,
                             email=c1_email,
                             telefono=c1_tel if c1_tel != 'None' else "",
                             empresa=empresa,
                             fecha_creacion=django.utils.timezone.now()
                         )
                else:
                    # No email, check by name?
                     if not Contacto.objects.filter(nombre=full_name, empresa=empresa).exists():
                         Contacto.objects.create(
                             nombre=full_name,
                             email="",
                             telefono=c1_tel if c1_tel != 'None' else "",
                             empresa=empresa,
                             fecha_creacion=django.utils.timezone.now()
                         )

            # Contact 2
            c2_nom = row_data.get(40, "").strip() # AO
            c2_ape = row_data.get(41, "").strip() # AP
            c2_email = row_data.get(42, "").strip() # AQ
            c2_tel = row_data.get(44, "").strip() # AS
            
            if c2_nom and c2_nom != 'None':
                full_name_2 = f"{c2_nom} {c2_ape}".strip()
                if c2_email and c2_email != 'None':
                     if not Contacto.objects.filter(email=c2_email, empresa=empresa).exists():
                         Contacto.objects.create(
                             nombre=full_name_2,
                             email=c2_email,
                             telefono=c2_tel if c2_tel != 'None' else "",
                             empresa=empresa,
                             fecha_creacion=django.utils.timezone.now()
                         )

        except Exception as outer_e:
            import sys
            sys.stderr.write(f"\nCRASH in Loop Row {i}: {outer_e}\n")
            raise outer_e

    print(f"Done. Created: {count_created}. Updated: {count_updated}.")

if __name__ == '__main__':
    run()
