import platform
from pathlib import Path

APP_NAME = "gsearch-mcp-cli"
CONFIG_DIR = Path.home() / f".{APP_NAME}"
CHROME_PROFILE_DIR = CONFIG_DIR / "chrome-profile"
CONFIG_FILE = CONFIG_DIR / "config.json"
PORT_MAP_FILE = CONFIG_DIR / "chrome-port-map.json"

GOOGLE_SEARCH_URL = "https://www.google.com/search"
GOOGLE_AI_MODE_PARAMS = {"udm": "50"}
GOOGLE_HOMEPAGE = "https://www.google.com/"
GOOGLE_ABOUT = "https://about.google/"
GOOGLE_PREFERENCES = "https://www.google.com/preferences"

REQUIRED_WARMUP_COOKIES = {"NID", "AEC"}

TIMEOUT_CHROME_LAUNCH = 15
TIMEOUT_PAGE_LOAD = 30
TIMEOUT_JS_EVAL = 10
TIMEOUT_SEARCH = 15
TIMEOUT_AI_MODE = 30
TIMEOUT_FETCH_BROWSER = 30
TIMEOUT_FETCH_HTTP = 15
TIMEOUT_WARMUP = 30
TIMEOUT_TAB_CLEANUP = 5

DEFAULT_RATE_LIMIT = 2.0
DEFAULT_BURST = 3
DEFAULT_MAX_TABS = 5


def _macos_browser_candidates() -> list[tuple[str, str]]:
    candidates = []
    entries = [
        ("Google Chrome", "Google Chrome.app/Contents/MacOS/Google Chrome"),
        ("Brave Browser", "Brave Browser.app/Contents/MacOS/Brave Browser"),
        ("Microsoft Edge", "Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
        ("Chromium", "Chromium.app/Contents/MacOS/Chromium"),
        ("Vivaldi", "Vivaldi.app/Contents/MacOS/Vivaldi"),
        ("Opera", "Opera.app/Contents/MacOS/Opera"),
        ("Opera GX", "Opera GX.app/Contents/MacOS/Opera GX"),
    ]
    for name, rel in entries:
        candidates.append((name, str(Path("/Applications") / rel)))
        candidates.append((name, str(Path.home() / "Applications" / rel)))
    return candidates


def _linux_browser_candidates() -> list[tuple[str, str]]:
    import shutil
    names = [
        ("Google Chrome", "google-chrome"),
        ("Google Chrome", "google-chrome-stable"),
        ("Chromium", "chromium"),
        ("Chromium", "chromium-browser"),
        ("Chromium (Snap)", "/snap/bin/chromium"),
        ("Brave Browser", "brave-browser"),
        ("Microsoft Edge", "microsoft-edge-stable"),
        ("Vivaldi", "vivaldi"),
    ]
    candidates = []
    for display, cmd in names:
        if cmd.startswith("/"):
            if Path(cmd).exists():
                candidates.append((display, cmd))
        else:
            path = shutil.which(cmd)
            if path:
                candidates.append((display, path))
    return candidates


def _windows_browser_candidates() -> list[tuple[str, str]]:
    import os
    program_files = os.environ.get("ProgramFiles", "C:\\Program Files")
    program_files_x86 = os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)")
    local_app_data = os.environ.get("LOCALAPPDATA", "")
    entries = [
        ("Google Chrome", "Google\\Chrome\\Application\\chrome.exe"),
        ("Brave Browser", "BraveSoftware\\Brave-Browser\\Application\\brave.exe"),
        ("Microsoft Edge", "Microsoft\\Edge\\Application\\msedge.exe"),
        ("Vivaldi", "Vivaldi\\Application\\vivaldi.exe"),
    ]
    candidates = []
    for name, rel in entries:
        for base in [program_files, program_files_x86, local_app_data]:
            if not base:
                continue
            full = Path(base) / rel
            if full.exists():
                candidates.append((name, str(full)))
    return candidates


def get_browser_candidates() -> list[tuple[str, str]]:
    system = platform.system()
    if system == "Darwin":
        return _macos_browser_candidates()
    elif system == "Linux":
        return _linux_browser_candidates()
    elif system == "Windows":
        return _windows_browser_candidates()
    return []


CHROME_BASE_FLAGS = [
    "--headless=new",
    "--no-first-run",
    "--no-default-browser-check",
    "--disable-extensions",
    "--disable-sync",
    "--disable-background-networking",
    "--remote-allow-origins=http://localhost",
    "--window-size=1280,900",
    "--disable-blink-features=AutomationControlled",
    "--disable-features=TranslateUI",
]

CHROME_PLATFORM_FLAGS = {
    "Linux": ["--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox"],
    "Darwin": ["--disable-gpu"],
    "Windows": ["--disable-gpu"],
}

PRIVATE_IPV4_RANGES = [
    "10.", "172.16.", "172.17.", "172.18.", "172.19.",
    "172.20.", "172.21.", "172.22.", "172.23.", "172.24.",
    "172.25.", "172.26.", "172.27.", "172.28.", "172.29.",
    "172.30.", "172.31.", "192.168.", "127.", "0.",
    "169.254.",
]

PRIVATE_IPV6_PREFIXES = [
    "::1",
    "fe80:",
    "fc00:",
    "fd00:",
    "::ffff:127.", "::ffff:10.", "::ffff:192.168.",
]

BLOCKED_HOSTS = {"metadata.google.internal", "169.254.169.254"}
ALLOWED_SCHEMES = {"http", "https"}
