import pandas as pd
import os
import re
import json
from datetime import date
from reportlab.lib.pagesizes import landscape, A4
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib import colors
try:
    import models_ as db
except:
    try:
        from . import models as db
    except:
        pass

pasta_bots=os.path.join(os.path.expanduser("~"), "api/estrutura_api/api/utils/bots")

class VerificarNT:
    def __init__(self, cnpj, mes):
        valor_notas=0
        qtd_notas=0
        notas_=[]
        print("modulo iniciado")
        with open(f"{pasta_bots}/controle/chave_nt.json", 'r', encoding='utf-8') as f:chaves_nt=json.load(f)
        emp=[list(i.keys())[0] for i in chaves_nt]
        cnpj,mes=(f'{cnpj}',f'{mes}')
        pasta_xls=os.path.join(os.path.expanduser("~"), f'.arquivos_api/{cnpj}/{mes}/2025/nfe')
        xls_emissor=os.listdir(os.path.join(pasta_xls, 'xls/emissor_xls') )
        xls_destinatario=os.listdir(os.path.join(pasta_xls, 'xls/destinatario_xls') )
        print(f"RETORNANDO EMPRESAS NO CHAVE_NT -> {emp}")
        #EMISSOR
        try:
            df=pd.read_excel(os.path.join(pasta_xls, f"xls/emissor_xls/{xls_emissor[0]}") )
            # for i in range(len(df.iloc[0:])):
            #     print(df.iloc[:i,3])

            #RETORNA O VALOR TOTAL DA PLANILHA
            # for i in df.iloc[0:, 24]:
            #     try:
            #         v=str(i).replace("R$","").replace(".","").replace(",",".").strip()
            #         print(f"Valor -> {float(v)}")
            #         if v!='nan':
            #             print("REQUESTE")
            #             valor_notas+=float(v)
            #     except:
            #         continue
            # print(f"VALOR TOTAL -> {valor_notas}")

            notas = []
            for i in df.iloc[0:, 3]:
                try:
                    notas.append(int(i))
                    qtd_notas+=1
                except:
                    continue
            
            for i in notas:
                print(f"nota emissor -> {i} - consta -> {os.path.isfile(os.path.join(pasta_xls, f'xml/xml_{i}.xml'))}")
                try:
                    if not os.path.isfile(os.path.join(pasta_xls, f'xml/xml_{i}.xml')):
                        notas_.append(i)
                        if isinstance(chaves_nt, list) and cnpj not in emp:
                            chaves_nt.append({f"{cnpj}":[i]})
                        elif isinstance(chaves_nt, list) and cnpj in emp:
                            chaves_nt[emp.index(f"{cnpj}")][f"{cnpj}"].append(i)

                except Exception as e:
                    print(f"Erro ao adicionar nota -> {e}")

            if len(notas_)==0 and cnpj in emp:
                chaves_nt[emp.index(f"{cnpj}")][f"{cnpj}"]=[]
            elif len(notas_)==0 and cnpj not in emp:
                chaves_nt.append({f"{cnpj}":[]})

            with open(f"{pasta_bots}/controle/chave_nt.json", 'w', encoding='utf-8') as f:json.dump(chaves_nt, f, indent=4, ensure_ascii=False)

        except Exception as e:
            print(f"Erro ao ler planilha -> {e}")
    
        #DESTINATARIO
        try:
            df=pd.read_excel(os.path.join(pasta_xls, f"xls/destinatario_xls/{xls_destinatario[0]}") )
            # for i in range(len(df.iloc[0:])):
            #     print(df.iloc[:i,3])
            
            #RETORNA O VALOR TOTAL DA PLANILHA
            # for i in df.iloc[0:, 24]:
            #     try:
            #         v=str(i).replace("R$","").replace(".","").replace(",",".").strip()
            #         print(f"Valor -> {float(v)}")
            #         if v!="nan":
            #             print("REQUESTE")
            #             valor_notas+=float(v)
            #     except:
            #         continue
            # print(f"VALOR TOTAL -> {valor_notas}")


            notas = []
            for i in df.iloc[0:, 3]:
                try:
                    notas.append(int(i))
                    qtd_notas+=1
                except:
                    continue
            
            for i in notas:
                print(f"nota destinatario -> {i} - consta -> {os.path.isfile(os.path.join(pasta_xls, f'xml/xml_{i}.xml'))}")
                try:
                    if not os.path.isfile(os.path.join(pasta_xls, f'xml/xml_{i}.xml')):
                        notas_.append(i)
                        if isinstance(chaves_nt, list) and cnpj not in emp:
                            chaves_nt.append({f"{cnpj}":[i]})
                        elif isinstance(chaves_nt, list) and cnpj in emp:
                            chaves_nt[emp.index(f"{cnpj}")][f"{cnpj}"].append(i)
                except Exception as e:
                    print(f"Erro ao adicionar nota -> {e}")

            if len(notas_)==0 and cnpj in emp:
                chaves_nt[emp.index(f"{cnpj}")][f"{cnpj}"]=[]
                chaves_nt[emp.index(f"{cnpj}")]["margem_err"]="0.00%"
                chaves_nt[emp.index(f"{cnpj}")]["qtd_notas"]=qtd_notas

            elif len(notas_)==0 and cnpj not in emp:
                chaves_nt.append({f"{cnpj}":[]})
                chaves_nt[emp.index(f"{cnpj}")]["margem_err"]="0.00%"
                chaves_nt[emp.index(f"{cnpj}")]["qtd_notas"]=qtd_notas

            elif len(notas_)>0:
                chaves_nt[emp.index(f"{cnpj}")]["margem_err"]=f"{(len(notas_)/qtd_notas)*100:.2f}%"
                chaves_nt[emp.index(f"{cnpj}")]["qtd_notas"]=qtd_notas
            



                print(f"notas faltantes -> {notas_}")
            print(f"RETORNAR INDICE EMPRESA -> {chaves_nt[emp.index(f"{cnpj}")]}")

            with open(f"{pasta_bots}/controle/chave_nt.json", 'w', encoding='utf-8') as f:json.dump(chaves_nt, f, indent=4, ensure_ascii=False)

        except Exception as e:
            print(f"Erro ao ler planilha -> {e}")

# VerificarNT("50893362000127", "10-out")

class GerarRelatorio:
    def __init__(self, caminho_saida):
        self.caminho_saida=caminho_saida
        os.makedirs(caminho_saida, exist_ok=True)

        with open(f"{pasta_bots}/controle/chave_nt.json", 'r', encoding='utf-8') as f:self.chaves_nt=json.load(f)
        self.emps=[list(i.keys())[0] for i in self.chaves_nt]
        self.pasta=str(caminho_saida).replace("/", " ").split()
        self.cnpj=str(self.pasta[-4])[-14:]
        ind={}
        for i, valor in enumerate(self.chaves_nt):ind.setdefault(list(valor.keys())[0], []).append(i)
        repetido={valor:idx for valor, idx in ind.items() if len(idx)>1}
        print(repetido)    

        return
    
    def gerar_arquivo(self):
        for ind,emp in enumerate(self.emps):
            try:
                if str(self.pasta[-4])[-14:]==emp:
                    row=660
                    print("GERANDO RELATORIO")
                    c=canvas.Canvas(f"{self.caminho_saida}/{db.SQLConn().parametro_readline(param=["cnpj", emp])["razao"]}_{str(int(date.today().month)-1)}.pdf", pagesize=(595.27, 841.89))
                    c.drawString(50, 830, "RELATORIO NFE's")
                    c.drawString(50, 780, f"Empresa: {db.SQLConn().parametro_readline(param=["cnpj", emp])["razao"]} | CNPJ: {emp}")
                    c.drawString(50, 730, f"Total Notas: {self.chaves_nt[ind]["qtd_notas"]} | Margem de Erro: {self.chaves_nt[ind]["margem_err"]}")
                    print(self.chaves_nt[ind])
                    if len(self.chaves_nt[ind][f"{emp}"])>0:
                        c.drawString(50, 680, f"Data: {date.today().isoformat()}")
                        c.drawString(50, 660, "Notas Faltantes:")
                        for i,nt in enumerate(self.chaves_nt[ind][f"{emp}"]):
                            row=row-20
                            c.drawString(50, row, f" {nt}")
                             
                    else:
                        c.drawString(50, 680, f"Data: {date.today().isoformat()}")
                    
                    c.showPage()
                    c.save()
            except:
                continue
        return

# GerarRelatorio(os.path.join(os.path.expanduser("~"), ".arquivos_api/38075745000192/10-out/2025/relatorios")).gerar_arquivo()
