from __future__ import annotations

import os
from pathlib import Path
from urllib.parse import urlparse

from dotenv import dotenv_values, load_dotenv


PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_E2E_ENV = "test"
VALID_E2E_ENVS = {"test", "prod"}
PROD_HOST_SUFFIXES = ("shunfju.com",)
TEST_HOST_SUFFIXES = ("lianlianwz.com",)


def e2e_env() -> str:
    value = os.getenv("E2E_ENV", DEFAULT_E2E_ENV).strip().lower()
    return value if value in VALID_E2E_ENVS else DEFAULT_E2E_ENV


def load_e2e_env(project_root: Path | None = None) -> str:
    root = project_root or PROJECT_ROOT
    shell_keys = set(os.environ)

    base_env = root / ".env"
    if base_env.exists():
        load_dotenv(base_env, override=False)

    selected_env = e2e_env()
    env_file = root / f".env.{selected_env}"
    if env_file.exists():
        for key, value in dotenv_values(env_file).items():
            if value is not None and key not in shell_keys:
                os.environ[key] = value

    os.environ.setdefault("E2E_ENV", selected_env)
    return selected_env


def is_production_env() -> bool:
    return e2e_env() == "prod"


def allow_env_url_mismatch() -> bool:
    return os.getenv("E2E_ALLOW_ENV_URL_MISMATCH", "").strip().lower() in {"1", "true", "yes", "on"}


def _host_matches(hostname: str, suffixes: tuple[str, ...]) -> bool:
    host = hostname.lower().rstrip(".")
    return any(host == suffix or host.endswith(f".{suffix}") for suffix in suffixes)


def _is_test_host(hostname: str) -> bool:
    host = hostname.lower().rstrip(".")
    return _host_matches(host, TEST_HOST_SUFFIXES) and (host.startswith("test-") or ".test-" in host)


def assert_url_allowed_for_env(url: str) -> None:
    if allow_env_url_mismatch():
        return

    parsed = urlparse(url)
    if parsed.scheme in {"", "about", "data", "blob", "file"}:
        return

    hostname = parsed.hostname or ""
    selected_env = e2e_env()
    if selected_env == "test" and _host_matches(hostname, PROD_HOST_SUFFIXES):
        raise AssertionError(
            f"E2E_ENV=test forbids production URL: {url}. "
            "Use test URLs/accounts, or set E2E_ALLOW_ENV_URL_MISMATCH=1 only for an explicit manual check."
        )
    if selected_env == "prod" and _is_test_host(hostname):
        raise AssertionError(
            f"E2E_ENV=prod forbids test URL: {url}. "
            "Use production URLs/accounts, or set E2E_ALLOW_ENV_URL_MISMATCH=1 only for an explicit manual check."
        )
