import os
import json
import arrow
import typing

from logging import getLogger, basicConfig, INFO
from config_isbank import Config
from pydantic import BaseModel

logger = getLogger(__name__)
basicConfig(filename=__name__, level=INFO)


class BankReceive(BaseModel):
    import_file_name: str
    iban: str
    bank_date: str
    channel_branch: str
    currency: typing.Optional[str] = "TL"
    currency_value: float
    bank_balance: float
    additional_balance: float
    process_name: str
    process_type: str
    process_comment: str
    bank_reference_code: str


def read_json_file(json_file_path):
    if os.path.exists(json_file_path):
        with open(json_file_path, "r") as json_file:
            return json.load(json_file)
    return {}


def write_json_file(json_file_path, data):
    with open(json_file_path, "w") as json_file:
        json.dump(data, json_file, indent=4)


def sender_service():
    parsed_data = read_json_file(Config.PARSED_PATH)
    if not parsed_data:
        print("Parsed data can not found")
        return

    if is_bank_retrieve_account_records(bank_data=json.dumps(parsed_data)):
        print("is_bank_retrieve_account_records is successful")
    else:
        print("is_bank_retrieve_account_records is failed")
        return

    today_date = str(arrow.now("GMT+0"))
    archive_path = str(Config.ARCHIVE_PATH + today_date + ".json").replace(" ", "")
    already_archived = read_json_file(archive_path)
    already_archived[today_date] = parsed_data
    write_json_file(archive_path, already_archived)
    write_json_file(Config.PARSED_PATH, {})
    return


def is_bank_retrieve_account_records(bank_data):
    from databases import AccountRecords

    data_bulk = json.loads(bank_data)
    print("data_bulk", data_bulk)
    new_record_list = []
    for data_keys in data_bulk:  # data_bulk is a dict
        for data_dict in data_bulk[data_keys]:  # data_bulk[data_keys] is a list
            data_dict["bank_balance"] = data_dict.pop("balance")
            data_dict["import_file_name"] = str(data_keys)
            print("data_dict before pyd", data_dict)
            data_dict = BankReceive(**data_dict).model_dump()
            print("data_dict after pyd", data_dict)
            new_account_record = AccountRecords.find_or_create(**data_dict)
            print("new_account_record.is_found", new_account_record.is_found)
            new_record_list.append(new_account_record.get_dict())
    if new_record_list:
        return True
    return False


# def send_request_to_api(data):
#     try:
#         headers = {"accept": "application/json", "Content-Type": "application/json"}
#         res = requests.post(url=Config.IP_ADDRESS, json=data, headers=headers)
#         if int(res.status_code) == 200:
#             return res.ok, res.json(), res.status_code
#     except Exception as e:
#         err = e
#         print('Exception',e)
#     return False, {}, 500
