import os
import secrets
import pytz
import redis
from apscheduler.jobstores.redis import RedisJobStore

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

def _to_bool(val, default: bool = False) -> bool:
    if val is None:
        return default
    if isinstance(val, bool):
        return val
    return str(val).strip().lower() in ("true", "1", "yes", "on", "t")

def _to_list(val, default: list = None) -> list:
    if val is None:
        return default or []
    if isinstance(val, list):
        return val
    return [item.strip() for item in str(val).split(",") if item.strip()]

class Config:
    DB_USER : str = os.environ.get("POSTGRES_USER", "vortexi")
    DB_PASSWORD : str = os.environ.get("POSTGRES_PASSWORD", "vortexipassword")
    DB_NAME : str = os.environ.get("POSTGRES_DB", "vortexidb")
    DB_HOST : str = os.environ.get("POSTGRES_HOST", "db")
    DB_PORT : str = os.environ.get("POSTGRES_PORT", "5432")
    SQLALCHEMY_DATABASE_URI : str = os.environ.get("DATABASE_URL") or os.environ.get("SQLALCHEMY_DATABASE_URI") or f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"

    FLASK_SESSION_KEY : str = os.environ.get("FLASK_SESSION_KEY", "7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f")
    AuthorizationKey : str = os.environ.get("AUTHORIZATION_KEY") or os.environ.get("AuthorizationKey", "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d")
    SWITCH_TO_ARGON_PASSWORD_HASH : bool = _to_bool(os.environ.get("SWITCH_TO_ARGON_PASSWORD_HASH"), True)

    REDIS_HOST : str = os.environ.get("REDIS_HOST", "redis")
    REDIS_PORT : int = int(os.environ.get("REDIS_PORT", 6379))
    REDIS_DB : int = int(os.environ.get("REDIS_DB", 0))
    SCHEDULER_JOBSTORES = {
        'default': RedisJobStore(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
    }
    SCHEDULER_TIMEZONE : pytz.timezone = pytz.utc
    REDIS_CLIENT = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)
    FLASK_LIMITED_STORAGE_URI : str = os.environ.get("FLASK_LIMITED_STORAGE_URI", f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}")

    BaseDomain : str = os.environ.get("BASE_DOMAIN") or os.environ.get("BaseDomain") or "localhost"
    BaseURL : str = os.environ.get("BASE_URL") or (f"http://{BaseDomain}:3003" if BaseDomain in ("localhost", "127.0.0.1") else f"https://www.{BaseDomain}")

    RCC_ACCESS_KEY : str = os.environ.get("RCC_ACCESS_KEY", "rcc_secret_key_12345")

    CloudflareTurnstileSiteKey : str = os.environ.get("CLOUDFLARE_TURNSTILE_SITE_KEY", "0x4AAAAAABQup2-ddXh4IHmv")
    CloudflareTurnstileSecretKey : str = os.environ.get("CLOUDFLARE_TURNSTILE_SECRET_KEY", "0x4AAAAAABQup8x54tvuzF_gqlubefQV7y4")

    DISCORD_CLIENT_ID : str = os.environ.get("DISCORD_CLIENT_ID", "1363965818328580157")
    DiscordBotToken : str = os.environ.get("DISCORD_BOT_TOKEN") or os.environ.get("DiscordBotToken") or "PleaseReplaceMeOneDay!"
    DISCORD_CLIENT_SECRET : str = os.environ.get("DISCORD_CLIENT_SECRET", "PleaseReplaceMeOneDay!")
    DISCORD_REDIRECT_URI : str = os.environ.get("DISCORD_REDIRECT_URI", f"{BaseURL}/settings/discord_handler")
    DISCORD_AUTHORIZATION_BASE_URL : str = "https://discord.com/api/oauth2/authorize"
    DISCORD_BOT_AUTHTOKEN : str = os.environ.get("DISCORD_BOT_AUTHTOKEN", "")
    DISCORD_BOT_AUTHORISED_IPS : list[str] = _to_list(os.environ.get("DISCORD_BOT_AUTHORISED_IPS"), ["127.0.0.1", "23.136.44.116", "2602:f6b7:0:7::a"])
    DISCORD_ADMIN_LOGS_WEBHOOK : str = os.environ.get("DISCORD_ADMIN_LOGS_WEBHOOK", "PleaseReplaceMeOneDay!")

    MAILJET_APIKEY : str = os.environ.get("MAILJET_APIKEY", "PleaseReplaceMeOneDay!")
    MAILJET_SECRETKEY : str = os.environ.get("MAILJET_SECRETKEY", "PleaseReplaceMeOneDay!")
    MAILJET_NOREPLY_SENDER : str = os.environ.get("MAILJET_NOREPLY_SENDER", f"no-reply@{BaseDomain}")
    MAILJET_DONATION_TEMPLATE_ID : int = int(os.environ.get("MAILJET_DONATION_TEMPLATE_ID", 6984478))
    MAILJET_EMAILVERIFY_TEMPLATE_ID : int = int(os.environ.get("MAILJET_EMAILVERIFY_TEMPLATE_ID", 6932923))
    MAILJET_PASSWORDRESET_TEMPLATE_ID : int = int(os.environ.get("MAILJET_PASSWORDRESET_TEMPLATE_ID", 6932939))

    KOFI_VERIFICATION_TOKEN : str = os.environ.get("KOFI_VERIFICATION_TOKEN", "")
    KOFI_ENABLED : bool = _to_bool(os.environ.get("KOFI_ENABLED"), False)

    VERIFIED_EMAIL_REWARD_ASSET : int = int(os.environ.get("VERIFIED_EMAIL_REWARD_ASSET", 197))
    ASSETMIGRATOR_ROBLOSECURITY : str = os.environ.get("ASSETMIGRATOR_ROBLOSECURITY", "")
    ASSETMIGRATOR_USE_PROXIES : bool = _to_bool(os.environ.get("ASSETMIGRATOR_USE_PROXIES"), False)
    ASSETMIGRATOR_PROXY_LIST_LOCATION : str = os.environ.get("ASSETMIGRATOR_PROXY_LIST_LOCATION", "./example_file.txt")

    RSA_PRIVATE_KEY_PATH : str = os.environ.get("RSA_PRIVATE_KEY_PATH", "./app/files/rsa_private_1024.pem")
    RSA_PRIVATE_KEY_PATH2 : str = os.environ.get("RSA_PRIVATE_KEY_PATH2", "./app/files/rsa_private_2048.pem")
    GAMESERVER_COMM_PRIVATE_KEY_LOCATION : str = os.environ.get("GAMESERVER_COMM_PRIVATE_KEY_LOCATION", "./app/files/rsa_private_gameserver.pem")

    USE_LOCAL_STORAGE : bool = _to_bool(os.environ.get("USE_LOCAL_STORAGE"), True)
    AWS_ACCESS_KEY : str = os.environ.get("AWS_ACCESS_KEY", "PleaseReplaceMeOneDay!")
    AWS_SECRET_KEY : str = os.environ.get("AWS_SECRET_KEY", "PleaseReplaceMeOneDay!")
    AWS_S3_BUCKET_NAME : str = os.environ.get("AWS_S3_BUCKET_NAME", "PleaseReplaceMeOneDay!")
    AWS_S3_ENDPOINT_URL : str = os.environ.get("AWS_S3_ENDPOINT_URL", "")
    AWS_S3_DOWNLOAD_CACHE_DIR : str = os.environ.get("AWS_S3_DOWNLOAD_CACHE_DIR", "./download_cache")
    R2_DOWNLOAD_CACHE_DIR : str = AWS_S3_DOWNLOAD_CACHE_DIR
    AWS_REGION_NAME : str = os.environ.get("AWS_REGION_NAME", "eu-north-1")
    AWS_S3_CACHE_LIFETIME : int = int(os.environ.get("AWS_S3_CACHE_LIFETIME", 3600))

    AWS_S3_CUSTOM_DOMAIN : str = os.environ.get("AWS_S3_CUSTOM_DOMAIN", "")
    r : str = AWS_S3_CUSTOM_DOMAIN
    CDN_URL : str = os.environ.get("CDN_URL") or (
        f"{BaseURL}/cdn_local" if USE_LOCAL_STORAGE else (
            f"https://{AWS_S3_CUSTOM_DOMAIN}" if AWS_S3_CUSTOM_DOMAIN and not AWS_S3_CUSTOM_DOMAIN.startswith("http")
            else (AWS_S3_CUSTOM_DOMAIN if AWS_S3_CUSTOM_DOMAIN else (f"{AWS_S3_ENDPOINT_URL}/{AWS_S3_BUCKET_NAME}" if AWS_S3_ENDPOINT_URL else f"https://{AWS_S3_BUCKET_NAME}.s3.{AWS_REGION_NAME}.amazonaws.com"))
        )
    )

    DISCOURSE_SSO_ENABLED : bool = _to_bool(os.environ.get("DISCOURSE_SSO_ENABLED"), False)
    DISCOURSE_FORUM_BASEURL : str = os.environ.get("DISCOURSE_FORUM_BASEURL", "")
    DISCOURSE_SECRET_KEY : str = os.environ.get("DISCOURSE_SECRET_KEY", "")

    ADMIN_GROUP_ID : int = int(os.environ.get("ADMIN_GROUP_ID", 1))
    FILTER_DISCORD_WEBHOOK : str = os.environ.get("FILTER_DISCORD_WEBHOOK", "PleaseReplaceMeOneDay!")
    ITEMRELEASER_DISCORD_WEBHOOK : str = os.environ.get("ITEMRELEASER_DISCORD_WEBHOOK", "PleaseReplaceMeOneDay!")
    ITEMRELEASER_ITEM_PING_ROLE_ID : int = int(os.environ.get("ITEMRELEASER_ITEM_PING_ROLE_ID", 1364011164387770553))
    WTF_CSRF_HEADERS : list[str] = ["x-csrf-token", "X-CSRFToken", "X-CSRF-Token"]
    CHEATER_REPORTS_DISCORD_WEBHOOK : str = os.environ.get("CHEATER_REPORTS_DISCORD_WEBHOOK", "PleaseReplaceMeOneDay!")

    PROMETHEUS_ENABLED : bool = _to_bool(os.environ.get("PROMETHEUS_ENABLED"), False)
    PROMETHEUS_ALLOWED_IPS : list[str] = _to_list(os.environ.get("PROMETHEUS_ALLOWED_IPS"), ["127.0.0.1"])

    ROLIMONS_API_ENABLED : bool = _to_bool(os.environ.get("ROLIMONS_API_ENABLED"), False)
    ROLIMONS_API_KEY : str = os.environ.get("ROLIMONS_API_KEY", "ExampleKey")

    CRYPTOMUS_PAYMENT_ENABLED : bool = _to_bool(os.environ.get("CRYPTOMUS_PAYMENT_ENABLED"), False)
    CRYPTOMUS_MERCHANT_ID : str = os.environ.get("CRYPTOMUS_MERCHANT_ID", "")
    CRYPTOMUS_API_KEY : str = os.environ.get("CRYPTOMUS_API_KEY", "")

    IPAPI_AUTH_KEY : str = os.environ.get("IPAPI_AUTH_KEY", "xxxxxxxxx")
    IPAPI_CACHE_LIFETIME : int = int(os.environ.get("IPAPI_CACHE_LIFETIME", 60 * 60 * 24))
    DEBUG_IPS : list[str] = _to_list(os.environ.get("DEBUG_IPS"), ["0.0.0.0", "127.0.0.1"])
