import os
import re
import subprocess
import time
import uuid
from pathlib import Path
from typing import Any

from bs4 import BeautifulSoup
from fastapi import FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import requests
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright


SERVICE_VERSION = "0.1.0"
HOST_BIND = "127.0.0.1"
PROFILE_ROOT = Path(os.getenv("HERMES_BROWSER_PROFILE_ROOT", r"C:\AI\browser_profiles"))
OUTPUT_ROOT = Path(os.getenv("HERMES_BROWSER_OUTPUT_ROOT", r"C:\AI\browser_outputs"))
TOKEN = os.getenv("HERMES_BROWSER_TOKEN", "").strip()
DEBUG_PORT = int(os.getenv("HERMES_BROWSER_DEBUG_PORT", "9223"))

PROFILE_REGISTRY: dict[str, dict[str, Any]] = {
    "edge-hermes": {
        "browser": "edge",
        "engine": "chromium",
        "name": "Hermes Edge profile",
        "channel": "msedge",
        "debug_port": 9223,
        "paths": [
            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
        ],
    },
    "chrome-hermes": {
        "browser": "chrome",
        "engine": "chromium",
        "name": "Hermes Chrome profile",
        "channel": "chrome",
        "debug_port": 9224,
        "paths": [r"C:\Program Files\Google\Chrome\Application\chrome.exe"],
    },
    "brave-hermes": {
        "browser": "brave",
        "engine": "chromium",
        "name": "Hermes Brave profile",
        "debug_port": 9225,
        "paths": [
            r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
            r"C:\Users\geron\AppData\Local\BraveSoftware\Brave-Browser\Application\brave.exe",
        ],
    },
    "vivaldi-hermes": {
        "browser": "vivaldi",
        "engine": "chromium",
        "name": "Hermes Vivaldi profile",
        "debug_port": 9226,
        "cdp_only": True,
        "paths": [
            r"C:\Program Files\Vivaldi\Application\vivaldi.exe",
            r"C:\Users\geron\AppData\Local\Vivaldi\Application\vivaldi.exe",
        ],
    },
    "opera-hermes": {
        "browser": "opera",
        "engine": "chromium",
        "name": "Hermes Opera profile",
        "debug_port": 9227,
        "paths": [
            r"C:\Program Files\Opera\opera.exe",
            r"C:\Users\geron\AppData\Local\Programs\Opera\opera.exe",
        ],
    },
    "yandex-hermes": {
        "browser": "yandex",
        "engine": "chromium",
        "name": "Hermes Yandex Browser profile",
        "debug_port": 9228,
        "paths": [
            r"C:\Program Files\Yandex\YandexBrowser\Application\browser.exe",
            r"C:\Users\geron\AppData\Local\Yandex\YandexBrowser\Application\browser.exe",
        ],
    },
    "firefox-hermes": {
        "browser": "firefox",
        "engine": "firefox",
        "name": "Hermes Firefox profile",
        "paths": [r"C:\Program Files\Mozilla Firefox\firefox.exe"],
    },
}

app = FastAPI(title="Hermes2 Local Browser Service", version=SERVICE_VERSION)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://work.mathchast.com", "http://localhost", "http://127.0.0.1"],
    allow_credentials=False,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["Content-Type", "X-Hermes-Token"],
)


class ExtractOptions(BaseModel):
    text: bool = True
    links: bool = True
    tables: bool = True
    screenshot: bool = False


class BrowseRequest(BaseModel):
    url: str
    profileId: str = "edge-hermes"
    mode: str = "read"
    waitUntil: str = "domcontentloaded"
    timeoutMs: int = Field(default=30000, ge=3000, le=120000)
    extract: ExtractOptions = Field(default_factory=ExtractOptions)


class OpenRequest(BaseModel):
    url: str
    profileId: str = "edge-hermes"


class ProfileCheckRequest(BaseModel):
    profileId: str = "edge-hermes"
    url: str = "https://example.com"
    timeoutMs: int = Field(default=30000, ge=3000, le=120000)


def require_token(x_hermes_token: str | None = Header(default=None)) -> None:
    if TOKEN and x_hermes_token != TOKEN:
        raise HTTPException(status_code=401, detail="Invalid browser service token")


def ensure_dirs() -> None:
    PROFILE_ROOT.mkdir(parents=True, exist_ok=True)
    OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)


def clean_text(value: str, limit: int = 60000) -> str:
    value = re.sub(r"\s+", " ", value).strip()
    return value[:limit]


def extract_links(soup: BeautifulSoup, base_url: str) -> list[dict[str, str]]:
    links: list[dict[str, str]] = []
    seen: set[str] = set()
    for item in soup.find_all("a"):
        href = (item.get("href") or "").strip()
        if not href or href.startswith(("javascript:", "mailto:", "tel:")):
            continue
        label = clean_text(item.get_text(" ", strip=True), limit=500)
        key = href
        if key in seen:
            continue
        seen.add(key)
        links.append({"href": href, "text": label})
        if len(links) >= 300:
            break
    return links


def extract_tables(soup: BeautifulSoup) -> list[dict[str, Any]]:
    tables: list[dict[str, Any]] = []
    for table in soup.find_all("table")[:20]:
        rows: list[list[str]] = []
        for tr in table.find_all("tr")[:100]:
            cells = [clean_text(cell.get_text(" ", strip=True), limit=1000) for cell in tr.find_all(["th", "td"])]
            if cells:
                rows.append(cells)
        if rows:
            tables.append({"rows": rows})
    return tables


def profile_path(profile_id: str) -> Path:
    safe = re.sub(r"[^a-zA-Z0-9_-]+", "-", profile_id).strip("-") or "edge-hermes"
    return PROFILE_ROOT / safe


def profile_config(profile_id: str) -> dict[str, Any]:
    safe = re.sub(r"[^a-zA-Z0-9_-]+", "-", profile_id).strip("-") or "edge-hermes"
    config = PROFILE_REGISTRY.get(safe)
    if not config:
        raise HTTPException(status_code=404, detail=f"Unknown browser profile: {profile_id}")
    return config


def browser_executable(config: dict[str, Any]) -> str | None:
    for candidate in config.get("paths") or []:
        if Path(candidate).exists():
            return str(candidate)
    return None


def edge_path() -> str:
    return browser_executable(PROFILE_REGISTRY["edge-hermes"]) or "msedge.exe"


def debug_url(port: int = DEBUG_PORT) -> str:
    return f"http://127.0.0.1:{port}"


def cdp_available(port: int = DEBUG_PORT) -> bool:
    try:
        response = requests.get(f"{debug_url(port)}/json/version", timeout=1)
        return response.ok
    except requests.RequestException:
        return False


def extract_page(page: Any, req: BrowseRequest, started: float, warnings: list[str], response: Any = None) -> dict[str, Any]:
    screenshot_path: str | None = None
    title = page.title()
    html = page.content()
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup(["script", "style", "noscript", "svg"]):
        tag.decompose()

    text = clean_text(soup.get_text(" ", strip=True)) if req.extract.text else ""
    links = extract_links(soup, req.url) if req.extract.links else []
    tables = extract_tables(soup) if req.extract.tables else []

    if req.extract.screenshot:
        image_path = OUTPUT_ROOT / f"browse_{uuid.uuid4().hex}.png"
        page.screenshot(path=str(image_path), full_page=True)
        screenshot_path = str(image_path)

    status = response.status if response is not None else None
    return {
        "ok": True,
        "url": page.url,
        "requestedUrl": req.url,
        "title": title,
        "html": html,
        "text": text,
        "links": links,
        "tables": tables,
        "screenshotPath": screenshot_path,
        "status": status,
        "warnings": warnings,
        "durationMs": int((time.perf_counter() - started) * 1000),
    }


def browse_existing_cdp(playwright: Any, req: BrowseRequest, started: float, warnings: list[str]) -> dict[str, Any] | None:
    config = profile_config(req.profileId)
    port = int(config.get("debug_port") or DEBUG_PORT)
    if not cdp_available(port):
        return None
    browser = playwright.chromium.connect_over_cdp(debug_url(port))
    try:
        context = browser.contexts[0] if browser.contexts else browser.new_context()
        page = context.pages[0] if context.pages else context.new_page()
        response = None
        if page.url == "about:blank" or page.url.rstrip("/") != req.url.rstrip("/"):
            response = page.goto(req.url, wait_until=req.waitUntil, timeout=req.timeoutMs)
        try:
            page.wait_for_load_state("networkidle", timeout=min(req.timeoutMs, 15000))
        except PlaywrightTimeoutError:
            warnings.append("networkidle timeout; extracted current open browser state")
        return extract_page(page, req, started, warnings, response=response)
    finally:
        browser.close()


def start_chromium_cdp(profile_id: str, url: str = "about:blank") -> subprocess.Popen[Any]:
    config = profile_config(profile_id)
    executable = browser_executable(config)
    if not executable:
        raise HTTPException(status_code=404, detail=f"Browser executable not found for profile: {profile_id}")
    port = int(config.get("debug_port") or DEBUG_PORT)
    return subprocess.Popen(
        [
            executable,
            f"--user-data-dir={profile_path(profile_id)}",
            f"--remote-debugging-port={port}",
            "--remote-allow-origins=*",
            "--no-first-run",
            url,
        ],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def wait_for_cdp(port: int, timeout_ms: int) -> None:
    deadline = time.perf_counter() + (timeout_ms / 1000)
    while time.perf_counter() < deadline:
        if cdp_available(port):
            return
        time.sleep(0.5)
    raise HTTPException(status_code=500, detail=f"CDP endpoint did not become ready on port {port}")


def browse_via_cdp(playwright: Any, req: BrowseRequest, started: float, warnings: list[str]) -> dict[str, Any]:
    config = profile_config(req.profileId)
    port = int(config.get("debug_port") or DEBUG_PORT)
    started_process: subprocess.Popen[Any] | None = None
    if not cdp_available(port):
        started_process = start_chromium_cdp(req.profileId)
        wait_for_cdp(port, req.timeoutMs)
    browser = playwright.chromium.connect_over_cdp(debug_url(port))
    try:
        context = browser.contexts[0] if browser.contexts else browser.new_context()
        page = context.pages[0] if context.pages else context.new_page()
        response = page.goto(req.url, wait_until=req.waitUntil, timeout=req.timeoutMs)
        try:
            page.wait_for_load_state("networkidle", timeout=min(req.timeoutMs, 15000))
        except PlaywrightTimeoutError:
            warnings.append("networkidle timeout; extracted current open browser state")
        result = extract_page(page, req, started, warnings, response=response)
        result["browserMode"] = "profile_cdp"
        return result
    finally:
        browser.close()
        if started_process is not None:
            started_process.terminate()


@app.get("/health")
def health(_: None = Header(default=None)) -> dict[str, Any]:
    return {"ok": True, "service": "local-browser-service", "version": SERVICE_VERSION}


@app.get("/profiles")
def profiles() -> dict[str, Any]:
    ensure_dirs()
    items: list[dict[str, Any]] = []
    for profile_id, config in PROFILE_REGISTRY.items():
        path = browser_executable(config)
        items.append(
            {
                "id": profile_id,
                "browser": config["browser"],
                "engine": config["engine"],
                "name": config["name"],
                "available": bool(path),
                "executablePath": path,
                "profilePath": str(profile_path(profile_id)),
            }
        )
    return {"profiles": items}


def launch_profile_context(playwright: Any, profile_id: str, timeout_ms: int) -> Any:
    config = profile_config(profile_id)
    path = browser_executable(config)
    if not path and not config.get("channel"):
        raise HTTPException(status_code=404, detail=f"Browser executable not found for profile: {profile_id}")
    kwargs: dict[str, Any] = {
        "user_data_dir": str(profile_path(profile_id)),
        "headless": False,
        "viewport": {"width": 1440, "height": 1000},
        "timeout": timeout_ms,
    }
    if config["engine"] == "chromium":
        kwargs["args"] = ["--disable-dev-shm-usage"]
        if path:
            kwargs["executable_path"] = path
        elif config.get("channel"):
            kwargs["channel"] = config["channel"]
        return playwright.chromium.launch_persistent_context(**kwargs)
    if config["engine"] == "firefox":
        if path and config.get("use_system_for_automation"):
            kwargs["executable_path"] = path
        return playwright.firefox.launch_persistent_context(**kwargs)
    raise HTTPException(status_code=400, detail=f"Unsupported browser engine: {config['engine']}")


@app.post("/browse")
def browse(req: BrowseRequest, x_hermes_token: str | None = Header(default=None)) -> dict[str, Any]:
    require_token(x_hermes_token)
    if req.mode != "read":
        raise HTTPException(status_code=400, detail="Only read mode is enabled")
    if not req.url.startswith(("http://", "https://")):
        raise HTTPException(status_code=400, detail="Only http/https URLs are allowed")

    ensure_dirs()
    started = time.perf_counter()
    warnings: list[str] = []

    try:
        with sync_playwright() as playwright:
            if profile_config(req.profileId).get("cdp_only"):
                return browse_via_cdp(playwright, req, started, warnings)

            existing = browse_existing_cdp(playwright, req, started, warnings)
            if existing is not None:
                existing["browserMode"] = "existing_cdp"
                return existing

            context = launch_profile_context(playwright, req.profileId, req.timeoutMs)
            page = context.new_page()
            response = None
            try:
                response = page.goto(req.url, wait_until=req.waitUntil, timeout=req.timeoutMs)
                try:
                    page.wait_for_load_state("networkidle", timeout=min(req.timeoutMs, 15000))
                except PlaywrightTimeoutError:
                    warnings.append("networkidle timeout; extracted current page state")
            except PlaywrightTimeoutError as exc:
                warnings.append(f"navigation timeout: {exc}")

            result = extract_page(page, req, started, warnings, response=response)
            result["browserMode"] = "temporary_persistent_context"
            context.close()
        return result
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Browser browse failed: {exc}") from exc


@app.post("/open")
def open_url(req: OpenRequest, x_hermes_token: str | None = Header(default=None)) -> dict[str, Any]:
    require_token(x_hermes_token)
    if not req.url.startswith(("http://", "https://")):
        raise HTTPException(status_code=400, detail="Only http/https URLs are allowed")
    ensure_dirs()
    config = profile_config(req.profileId)
    executable = browser_executable(config)
    if not executable:
        raise HTTPException(status_code=404, detail=f"Browser executable not found for profile: {req.profileId}")
    if config["engine"] == "firefox":
        args = [executable, "-profile", str(profile_path(req.profileId)), req.url]
    else:
        port = int(config.get("debug_port") or DEBUG_PORT)
        args = [
            executable,
            f"--user-data-dir={profile_path(req.profileId)}",
            f"--remote-debugging-port={port}",
            "--remote-allow-origins=*",
            req.url,
        ]
        args = [item for item in args if item]
    subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return {
        "ok": True,
        "url": req.url,
        "profileId": req.profileId,
        "browser": config["browser"],
        "debugPort": config.get("debug_port"),
        "message": "Opened in local browser profile for manual user action.",
    }


@app.post("/profile-check")
def profile_check(req: ProfileCheckRequest, x_hermes_token: str | None = Header(default=None)) -> dict[str, Any]:
    require_token(x_hermes_token)
    if not req.url.startswith(("http://", "https://")):
        raise HTTPException(status_code=400, detail="Only http/https URLs are allowed")
    ensure_dirs()
    started = time.perf_counter()
    config = profile_config(req.profileId)
    try:
        with sync_playwright() as playwright:
            if config.get("cdp_only"):
                port = int(config.get("debug_port") or DEBUG_PORT)
                started_process: subprocess.Popen[Any] | None = None
                if not cdp_available(port):
                    started_process = start_chromium_cdp(req.profileId)
                    wait_for_cdp(port, req.timeoutMs)
                browser = playwright.chromium.connect_over_cdp(debug_url(port))
                context = browser.contexts[0] if browser.contexts else browser.new_context()
                page = context.pages[0] if context.pages else context.new_page()
                response = page.goto(req.url, wait_until="domcontentloaded", timeout=req.timeoutMs)
            else:
                context = launch_profile_context(playwright, req.profileId, req.timeoutMs)
                page = context.new_page()
                browser = None
                started_process = None
                response = page.goto(req.url, wait_until="domcontentloaded", timeout=req.timeoutMs)
            signals = page.evaluate(
                """() => ({
                    userAgent: navigator.userAgent,
                    language: navigator.language,
                    languages: navigator.languages,
                    platform: navigator.platform,
                    webdriver: navigator.webdriver,
                    cookieEnabled: navigator.cookieEnabled,
                    doNotTrack: navigator.doNotTrack,
                    hardwareConcurrency: navigator.hardwareConcurrency,
                    deviceMemory: navigator.deviceMemory,
                    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                    screen: {
                        width: screen.width,
                        height: screen.height,
                        availWidth: screen.availWidth,
                        availHeight: screen.availHeight,
                        colorDepth: screen.colorDepth,
                        pixelDepth: screen.pixelDepth
                    },
                    viewport: {
                        width: window.innerWidth,
                        height: window.innerHeight,
                        devicePixelRatio: window.devicePixelRatio
                    }
                })"""
            )
            result = {
                "ok": True,
                "profileId": req.profileId,
                "browser": config["browser"],
                "engine": config["engine"],
                "url": page.url,
                "status": response.status if response is not None else None,
                "title": page.title(),
                "profilePath": str(profile_path(req.profileId)),
                "executablePath": browser_executable(config),
                "signals": signals,
                "durationMs": int((time.perf_counter() - started) * 1000),
            }
            if browser is not None:
                browser.close()
            else:
                context.close()
            if started_process is not None:
                started_process.terminate()
            return result
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Profile check failed: {exc}") from exc
