import json
import os
from datetime import datetime
from pathlib import Path

from requests_oauthlib import OAuth2Session

import mazda_upload
from mazda_archive import archive_files
from mazda_export import convert_csv, export_orders


def get_config():
    base_dir = str(Path.cwd())
    cfg = {
        "timestamp": "",
        "base_dir": base_dir,
        "data_dir": base_dir + "\\data",
        "export_dir": base_dir + "\\export\\Mazda",
        "temp_dir": base_dir + "\\export\\Mazda\\temp",
    }
    os.makedirs(cfg["temp_dir"], exist_ok=True)
    os.makedirs(cfg["data_dir"], exist_ok=True)
    os.makedirs(f"{cfg["export_dir"]}\\error", exist_ok=True)
    os.makedirs(f"{cfg["export_dir"]}\\success", exist_ok=True)
    os.makedirs(f"{cfg["base_dir"]}\\logs", exist_ok=True)
    os.makedirs(f"{cfg["base_dir"]}\\temp", exist_ok=True)
    return cfg


def token_load(config) -> mazda_upload.Token:
    try:
        with open(config["base_dir"] + "\\temp\\token.json", "r") as frh:
            return json.load(frh)
    except FileNotFoundError:
        return None


def submit_changes(config):
    oauth = OAuth2Session(mazda_upload.cfg_prod.client_id, token=token_load(config))
    if oauth.authorized:
        mazda_upload.upload_files(mazda_upload.cfg_prod, oauth, config["export_dir"])
    else:
        print("OAuth2 session not authorized. Please check your credentials.")
        return


def main():
    config = get_config()
    dt = datetime.now()
    config["timestamp"] = dt.strftime("%Y%m%d_%H%M%S")
    print("Start: " + dt.strftime("%d.%m.%Y %H:%M:%S"))

    print("Export")
    data = convert_csv(
        config["data_dir"] + "\\Workshop_Order_Report.csv", config["temp_dir"] + "\\mazda_export.json", 2024, 1
    )
    export_orders(data, config["temp_dir"])

    print("Archivierung")
    archive_files(config["export_dir"])

    print("Upload")
    submit_changes(config)


if __name__ == "__main__":
    main()
