import os
import requests

from dotenv import load_dotenv
from services.profile_manager import load_profile


load_dotenv()


APP_ID = os.getenv("APP_ID")
TOKEN = os.getenv("TOKEN")
UID = os.getenv("UID")


def build_dynamic(profile):

    dynamic = []


    # ======================
    # TEXT DYNAMIC
    # ======================

    old_dynamic = profile.get(
        "dynamic",
        []
    )


    for item in old_dynamic:

        if item.get("name") in [
            "time",
            "sub2",
            "sub3"
        ]:

            dynamic.append(
                {
                    "type": 1,
                    "name": item["name"],
                    "value": item["value"]
                }
            )


    # ======================
    # ATTACHMENTS
    # ======================

    attachments = profile.get(
        "attachments",
        []
    )


    for index, attach in enumerate(
        attachments,
        start=1
    ):

        if not attach:
            continue


        if attach.get("name"):

            dynamic.append(
                {
                    "type": 1,
                    "name": f"attach_{index}_name",
                    "value": attach["name"]
                }
            )


        if attach.get("description"):

            dynamic.append(
                {
                    "type": 1,
                    "name": f"attach_{index}_description",
                    "value": attach["description"]
                }
            )


        if attach.get("icon"):

            dynamic.append(
                {
                    "type": 3,
                    "name": f"attach_{index}_icon",
                    "value": {
                        "url": attach["icon"]
                    }
                }
            )


        if attach.get("mini_icon"):

            dynamic.append(
                {
                    "type": 3,
                    "name": f"attach_{index}_mini_icon",
                    "value": {
                        "url": attach["mini_icon"]
                    }
                }
            )


    return dynamic



def sync():

    profile = load_profile()


    payload = {

        "username": profile.get(
            "username",
            "Profile Widget"
        ),

        "data": {

            "dynamic": build_dynamic(profile)

        }

    }


    print(
        "PAYLOAD:",
        payload,
        flush=True
    )


    url = (
        "https://discord.com/api/v9/"
        f"applications/{APP_ID}/users/"
        f"{UID}/identities/0/profile"
    )


    headers = {

        "Authorization":
            f"Bot {TOKEN}",

        "User-Agent":
            "DiscordBot (https://github.com/discord/discord-api-docs, 1.0.0)",

        "Content-Type":
            "application/json"

    }


    print(
        "PATCH START",
        flush=True
    )


    try:

        response = requests.patch(
            url,
            json=payload,
            headers=headers,
            timeout=20
        )


        print(
            "PATCH END",
            response.status_code,
            response.text,
            flush=True
        )


        return response


    except Exception as e:

        print(
            "PATCH ERROR",
            repr(e),
            flush=True
        )


        return None
