
import uuid
from datetime import datetime
from decimal import Decimal
from satcfdi.models import Signer
from satcfdi.create.cfd import cfdi40, cartaporte31
from satcfdi.create.addendas import dvz11
from satcfdi.create.cfd.catalogos import RegimenFiscal, UsoCFDI, MetodoPago, Impuesto, TipoFactor

from satcfdi.cfdi import CFDI
from satcfdi import render
from satcfdi.pacs import Environment, PAC , Accept



from satcfdi.pacs.finkok import Finkok
pac = Finkok(username="finkok@gsttransportes.com", password="P1$$w0rd#.", environment=Environment.TEST)


def get_idccp():
    uuid_v4 = uuid.uuid4()
    custom_uuid_str = f"CCC{uuid_v4.hex[3:8].upper()}-{uuid_v4.hex[8:12].upper()}-{uuid_v4.hex[12:16].upper()}-{uuid_v4.hex[16:20].upper()}-{uuid_v4.hex[20:32].upper()}"
    return custom_uuid_str

idcpp = get_idccp()

print(idcpp)
print(RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES)

# Load signing certificate
signer = Signer.load(
    certificate=open('csd/Personas Morales/IVD920810GU2_CSD.cer', 'rb').read(),
    key=open('csd/Personas Morales/IVD920810GU2_CSD.key', 'rb').read(),
    password=open('csd/Personas Morales/IVD920810GU2_CSD.txt', 'r').read()
)


# create Comprobante
invoice = cfdi40.Comprobante(
    emisor=cfdi40.Emisor(
        rfc=signer.rfc,
        nombre="INNOVACION VALOR Y DESARROLLO SA",
        regimen_fiscal=RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES
    ),
    receptor=cfdi40.Receptor(
        rfc='GCA000415UX7',
        nombre='GRUPO DE CONSTRUCCION ARQUITECTONICA NACIONAL',
        uso_cfdi=UsoCFDI.GASTOS_EN_GENERAL,
        domicilio_fiscal_receptor="11830",
        regimen_fiscal_receptor=RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES
    ),
    lugar_expedicion="58000",
    tipo_de_comprobante='I',
    forma_pago='99',
    metodo_pago=MetodoPago.PAGO_EN_PARCIALIDADES_O_DIFERIDO,
    condiciones_de_pago="30",
    serie="FTEI",
    folio="12803",
    conceptos=[
        cfdi40.Concepto(
            clave_prod_serv='78101802',
            cantidad=Decimal('1.00'),
            clave_unidad='E48',
            descripcion='FLETES',
            valor_unitario=Decimal('22250.30'),
            impuestos=cfdi40.Impuestos(
                traslados=cfdi40.Traslado(
                        impuesto=Impuesto.IVA,
                        tipo_factor=TipoFactor.TASA,
                        tasa_o_cuota=Decimal('0.160000'),
                    ),
                retenciones=[
                    # cfdi40.Retencion(
                    #     impuesto=Impuesto.ISR,
                    #     tipo_factor=TipoFactor.TASA,
                    #     tasa_o_cuota=Decimal('0.100000'),
                    # ),
                    cfdi40.Retencion(
                        impuesto=Impuesto.IVA,
                        tipo_factor=TipoFactor.TASA,
                        tasa_o_cuota=Decimal('0.040000'),
                    )
                ],
            )
        )
    ],
    complemento=cartaporte31.CartaPorte(
        id_ccp = f"{idcpp}",
        transp_internac='No', 
        total_dist_rec='2291.00',
        # TODO Ubicaciones
        ubicaciones=[
                cartaporte31.Ubicacion(
                    tipo_ubicacion='Origen', 
                    id_ubicacion="OR000001",
                    rfc_remitente_destinatario="BPU7901018D4",
                    nombre_remitente_destinatario="BEBIDAS PURIFICADAS S DE RL DE CV -XD NORTE ALLIUZ",
                    fecha_hora_salida_llegada=datetime.fromisoformat("2022-09-22T12:00:00"),
                    domicilio=cartaporte31.Domicilio(
                        calle='calle dos int 5a',
                        numero_exterior='2323',
                        estado='NLE', 
                        pais='MEX', 
                        codigo_postal='66480'
                    ),
                ),
                cartaporte31.Ubicacion(
                    tipo_ubicacion='Destino', 
                    id_ubicacion="DE000001",
                    rfc_remitente_destinatario="CCO8605231N4",
                    nombre_remitente_destinatario="Cadena comercial oxxo",
                    fecha_hora_salida_llegada=datetime.fromisoformat("2022-09-22T12:00:00"),
                    distancia_recorrida="2291.00",
                    domicilio=cartaporte31.Domicilio(
                        calle='corredor tijuana rosarito',
                        numero_exterior='24602',
                        estado='BCN,', 
                        pais='MEX', 
                        codigo_postal='22236',
                    ),
                ),

        ],
        # TODO Mercancias -> Productos
        mercancias=cartaporte31.Mercancias(
                peso_bruto_total="26356.550", 
                unidad_peso="KGM", 
                num_total_mercancias="3",
                mercancia=[
                    cartaporte31.Mercancia(
                        bienes_transp="24112701", 
                        descripcion="Pallets de madera", 
                        cantidad="26.000000", 
                        clave_unidad="H87", 
                        unidad='Pieza',
                        peso_en_kg="858.00",
                        valor_mercancia="0.000000",
                        moneda="MXN",
                    ),
                    cartaporte31.Mercancia(
                        bienes_transp="50202301", 
                        descripcion="Agua", 
                        cantidad="1370.000000", 
                        clave_unidad="XBX", 
                        unidad="Caja",
                        peso_en_kg="22909.00",
                        valor_mercancia="0.000000",
                        moneda="MXN",
                    ),
                    cartaporte31.Mercancia(
                        bienes_transp="50202300", 
                        descripcion="Beverages", 
                        cantidad="590.000000", 
                        clave_unidad="XBX", 
                        unidad="Caja",
                        peso_en_kg="2589.550",
                        valor_mercancia="0.000000",
                        moneda="MXN",
                    ),
                ],

                autotransporte=cartaporte31.Autotransporte(
                    perm_sct="TPAF01", 
                    num_permiso_sct="2838", 
                    identificacion_vehicular=cartaporte31.IdentificacionVehicular(
                        config_vehicular="T3S2", 
                        peso_bruto_vehicular="44.36", 
                        placa_vm="97BA4D", 
                        anio_modelo_vm="2024"
                    ), 
                    seguros=cartaporte31.Seguros(asegura_resp_civil="SEGUROS ELPHM S.A", poliza_resp_civil="DI9-XXX"),
                    remolques=cartaporte31.Remolque(sub_tipo_rem="CTR007", placa="29UJ4L"),
                ),

        ),  # MERCANCIAS
        figura_transporte=cartaporte31.TiposFigura(
                tipo_figura="01", 
                nombre_figura="PEREZ RAMIREZ FERNANDO",
                rfc_figura="PERF870116KK5",
                num_licencia="DF00178004" ,
        ),
    ),
# ... ADD MORE ...
    # # TODO Working Addenum example
    # addenda=dvz11.Diverza(
    #     generales=dvz11.Generales(
    #         tipo_documento="Factura"
    #     )
    # )

) # Complemento

#print(invoice)
invoice.sign(signer)
invoice = invoice.process()
print(invoice)

##################################################################
# NOTE MANUAL STAGE
##################################################################
# # # XML
# xml = invoice.xml_bytes()
# # # save to file
# invoice.xml_write("folio_comprobante_124.xml")
# pdf = render.pdf_bytes(invoice)
# # # save to file
# render.pdf_write(invoice, "xxa_comprobante_.pdf")
# # # 
##################################################################
doc = pac.stamp(invoice, accept=Accept.XML)
with open('x_stamped_.xml', 'wb') as f:
    f.write(doc.xml)
# catch signed xml from file
inv = CFDI.from_file('x_stamped_.xml')

pdf = render.pdf_bytes(inv)
render.pdf_write(inv, "xxxxaz_comprobante_.pdf")



