from decouple import config
from pathlib import Path
import re
import requests
import sys
import json


def format_cpf(cpf: str) -> str:
    """
        Formata o CPF para remover caracteres não numéricos e ajusta o comprimento para 11 dígitos.

        Parâmetros:
            cpf (str): O CPF a ser formatado.

        Retorna:
            str: O CPF formatado.
    """
    formated_cpf = re.sub(r'[^0-9]', '', cpf)

    if not formated_cpf:
        return formated_cpf

    while len(formated_cpf) < 11:
        formated_cpf = '0' + formated_cpf

    if len(formated_cpf) > 11:
        formated_cpf = formated_cpf[:11]

    return formated_cpf


def get_token(username: str, password: str) -> str:
    """
        Obtém o token de autenticação para acessar a API da Receita Federal.

        Parâmetros:
            username (str): O nome de usuário para autenticação.
            password (str): A senha para autenticação.

        Retorna:
            str: O token de autenticação.
    """
    url = 'https://api-parceiro.bancomaster.com.br/token'

    data = {
        'usuario': username,
        'senha': password
    }

    response = requests.post(url, json=data)

    return response.json().get('accessToken')


def get_data(cpf: str, token: str) -> dict:
    """
        Obtém os dados do CPF informado.

        Parâmetros:
            cpf (str): O CPF a ser consultado.
            token (str): O token de autenticação.

        Retorna:
            dict: Os dados do CPF consultado.
    """
    url = f'https://api-parceiro.bancomaster.com.br/cartoes/v1/consulta-limite?cpf={cpf}'

    headers = {
        'Authorization': f'Bearer {token}'
    }

    try:
        response = requests.get(url, headers=headers)

        print('---->', response.json())
        
        return response.json()
    except json.JSONDecodeError:
        return {'erro': response.text}


if __name__ == '__main__':
    BASE_DIR = Path(__file__).resolve().parent.parent
    USERNAME = config('USUARIO')
    PASSWORD = config('SENHA')

    with open(BASE_DIR / 'erro.txt', 'w') as file:
        pass

    try:
        with open(BASE_DIR / 'cpf_cliente.txt', 'r') as file:
            cpf = format_cpf(file.readline().strip())
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao ler cpf: {e}.')

        sys.exit(f'Erro ao ler cpf: {e}.')

    try:
        with open(BASE_DIR / 'limite_consultas_diarias.txt', 'r') as file:
            limite = int(file.readline().strip())
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao ler limite de consultas diárias: {e}.')

        sys.exit(f'Erro ao ler limite de consultas diárias: {e}.')
    
    if limite <= 0:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Limite de consultas diárias atingido.')

        sys.exit('Limite de consultas diárias atingido.')

    cpf_blacklist = []

    # try:
    #     with open(BASE_DIR / 'blacklist.csv', 'r') as file:
    #         # IGNORANDO CABEÇALHO
    #         file.readline()

    #         for line in file:
    #             cpf_blacklist.append(format_cpf(line.strip()))
    # except Exception as e:
    #     with open(BASE_DIR / 'erro.txt', 'w') as file:
    #         file.write(f'Erro ao ler blacklist: {e}.')

    #     sys.exit(f'Erro ao ler blacklist: {e}.')

    if cpf in cpf_blacklist:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'CPF na blacklist.')

        sys.exit('CPF na blacklist.')

    try:
        token = get_token(USERNAME, PASSWORD)
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao obter token: {e}.')

        sys.exit(f'Erro ao obter token: {e}.')

    try:
        data = get_data(cpf, token)
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao obter dados: {e}.')

        sys.exit(f'Erro ao obter dados: {e}.')

    limite -= 1
    try:
        with open(BASE_DIR / 'limite_consultas_diarias.txt', 'w') as file:
            file.write(f'{limite}')
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao atualizar limite de consultas diárias: {e}.')

    try:
        with open(BASE_DIR / 'dados.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except Exception as e:
        with open(BASE_DIR / 'erro.txt', 'w') as file:
            file.write(f'Erro ao escrever dados: {e}.')

