from __future__ import annotations

import os
from pathlib import Path
from typing import Literal, cast

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.remote.webdriver import WebDriver

BrowserName = Literal["chrome", "firefox"]


class WebDriverUnavailableError(RuntimeError):
    pass


def _env_bool(name: str, default: bool) -> bool:
    raw = os.getenv(name)
    if raw is None:
        return default
    value = raw.strip().lower()
    if value in {"1", "true", "yes", "y", "on"}:
        return True
    if value in {"0", "false", "no", "n", "off"}:
        return False
    return default


def _resolve_driver_path(env_name: str) -> str | None:
    raw = os.getenv(env_name)
    if not raw:
        return None
    path = Path(raw).expanduser()
    return str(path)


def create_webdriver(
    *,
    browser: BrowserName | None = None,
    headless: bool | None = None,
) -> WebDriver:
    raw_browser = (browser or os.getenv("SELENIUM_BROWSER", "chrome")).strip().lower()
    if raw_browser not in {"chrome", "firefox"}:
        raise ValueError(f"不支持的浏览器类型：{raw_browser!r}（仅支持 chrome/firefox）")

    selected_browser = cast(BrowserName, raw_browser)

    use_headless = _env_bool("SELENIUM_HEADLESS", True) if headless is None else headless

    try:
        if selected_browser == "chrome":
            options = ChromeOptions()
            if use_headless:
                options.add_argument("--headless")
            options.add_argument("--window-size=1280,720")
            options.add_argument("--disable-gpu")

            driver_path = _resolve_driver_path("CHROMEDRIVER_PATH")
            if driver_path:
                service = ChromeService(executable_path=driver_path)
                driver = webdriver.Chrome(service=service, options=options)
            else:
                driver = webdriver.Chrome(options=options)

        else:
            options = FirefoxOptions()
            options.headless = use_headless

            driver_path = _resolve_driver_path("GECKODRIVER_PATH")
            if driver_path:
                service = FirefoxService(executable_path=driver_path)
                driver = webdriver.Firefox(service=service, options=options)
            else:
                driver = webdriver.Firefox(options=options)

        driver.set_page_load_timeout(15)
        return driver
    except WebDriverException as exc:
        raise WebDriverUnavailableError(
            "WebDriver 启动失败：请确认已安装浏览器与对应驱动；"
            "或设置环境变量 CHROMEDRIVER_PATH/GECKODRIVER_PATH 指向驱动可执行文件。"
        ) from exc
    except RuntimeError as exc:
        message = str(exc)
        if "Can't find free port" in message or "Unable to bind" in message:
            raise WebDriverUnavailableError(
                "WebDriver 启动失败：当前环境不允许创建本地监听端口（socket bind 被拒绝）。"
            ) from exc
        raise


def to_file_url(path: Path) -> str:
    return path.resolve().as_uri()
