# websites domain
import glob
import os
from enum import StrEnum

from constants.constants import URLS_DIR, URLS_FILE_TEMPLATE

CLASSIFIEDS_RESET_TOKEN = "4b61655535e7ed388f0d40a93600254c"


class Website(StrEnum):
    HOMEPAGE = "homepage"
    SHOPPING = "shopping"
    CLASSIFIEDS = "classifieds"
    REDDIT = "reddit"
    WIKIPEDIA = "wikipedia"
    SHOPPING_ADMIN = "shopping_admin"
    GITLAB = "gitlab"
    MAP = "map"


URL_MAPPINGS_FLAT: list[tuple[Website, str, str]] = []

ACCOUNTS = {
    Website.REDDIT: {"username": "MarvelsGrantMan136", "password": "test1234"},
    Website.SHOPPING: {
        "username": "emma.lopez@gmail.com",
        "password": "Password.123",
    },
    Website.CLASSIFIEDS: {
        "username": "blake.sullivan@gmail.com",
        "password": "Password.123",
    },
    Website.SHOPPING_ADMIN: {"username": "admin", "password": "admin1234"},
    Website.GITLAB: {"username": "byteblaze", "password": "hello1234"},
}

# NOTE: expanded to more than one URL mapping. Using `reddit.com` leads to API blocking, using postmill instead;
# agent might still generate `reddit.com` due to the phrasing in task intents (e.g.: asking for a "subrreddit")

URL_MAPPINGS = {
    Website.HOMEPAGE: ["http://homepage.com"],
    Website.SHOPPING: ["http://onestopmarket.com"],
    Website.REDDIT: [
        "http://reddit.com",
        "http://postmill.com",  # "http://freddit.com"
    ],
    Website.WIKIPEDIA: ["http://wikipedia.org"],
    Website.CLASSIFIEDS: ["http://classifieds.com"],
    Website.SHOPPING_ADMIN: ["http://luma.com/admin"],
    Website.GITLAB: ["http://gitlab.com"],
    Website.MAP: ["http://openstreetmap.org"],
}

LOCAL_URLS_NORM: dict[Website, str] = {}

PAGE_NAME_NORMALIZATIONS = {
    Website.WIKIPEDIA: ("User:The other Kiwix guy/Landing", "Welcome to Wikipedia"),
}

SITE_NAMES = {
    Website.REDDIT: ["Reddit"],
    Website.SHOPPING: ["One Stop Market", "shopping"],
    Website.HOMEPAGE: ["Homepage"],
    Website.CLASSIFIEDS: ["Classifieds"],
    Website.GITLAB: ["GitLab"],
    Website.MAP: ["Map"],
}

VWA_DOMAINS = [
    Website.HOMEPAGE,
    Website.SHOPPING,
    Website.REDDIT,
    Website.WIKIPEDIA,
    Website.CLASSIFIEDS,
]

WA_DOMAINS = [
    Website.HOMEPAGE,
    Website.SHOPPING,
    Website.REDDIT,
    Website.SHOPPING_ADMIN,
    Website.GITLAB,
    Website.MAP,
    Website.WIKIPEDIA,
]

NO_COOKIE_RESET_SITES = [Website.WIKIPEDIA, Website.HOMEPAGE, Website.MAP]


def set_local_url_mappings(instance_id: int):
    global URL_MAPPINGS_FLAT, LOCAL_URLS_NORM
    website_urls = get_website_urls_from_file(instance_id)

    url_mappings_flat = []
    for website, instance_url in website_urls.items():
        for real_url in URL_MAPPINGS[website]:
            url_mappings_flat.append((website, instance_url, real_url))

        if website == Website.WIKIPEDIA:
            LOCAL_URLS_NORM[website] = instance_url + "/wikipedia_en_all_maxi_2022-05"
        else:
            LOCAL_URLS_NORM[website] = instance_url
    URL_MAPPINGS_FLAT = url_mappings_flat


def get_url_from_file(website: Website, instance_id: int) -> str:
    """Get the URL for a given website and instance ID from the URLs file."""
    url_file = URLS_FILE_TEMPLATE.format(PROCESS_ID=instance_id)
    if not os.path.exists(url_file):
        return ""
    with open(url_file) as urls_file:
        lines = urls_file.readlines()
    line = next(line for line in lines if line.startswith(f"{website}-{instance_id}"))
    url = line.split(" ")[1].strip()
    return url


def get_website_urls_from_file(instance_id: int) -> dict[Website, str]:
    """Get the list of websites that are being hosted."""
    site_urls = {}
    url_file = URLS_FILE_TEMPLATE.format(PROCESS_ID=instance_id)
    with open(url_file) as urls_file:
        lines = urls_file.readlines()
    for line in lines:
        instance_id = int(line.split(" ")[0].split("-")[1])
        if instance_id == instance_id:
            website_name = line.split("-")[0]
            site_urls[Website(website_name)] = line.split(" ")[1].strip()
    return site_urls


def get_username(website: Website) -> str:
    """Get the username for a given website."""
    username = ACCOUNTS[website]["username"]
    return username


def get_username_and_password(website: Website) -> tuple[str, str]:
    """Get the username and password for a given website."""
    username = ACCOUNTS[website]["username"]
    password = ACCOUNTS[website]["password"]
    return username, password


def get_local_url_norm(website: Website) -> str:
    if website in LOCAL_URLS_NORM:
        return LOCAL_URLS_NORM[website]
    else:
        raise ValueError(f"Website {website} not found in LOCAL_URLS_NORM")
