"""Browser history sensor."""

from __future__ import annotations

import os
import platform
import shutil
import sqlite3
import tempfile
import time
from pathlib import Path

from neurovault.sensors.base import BaseSensor


class BrowserSensor(BaseSensor):
    """Read browser history from local browser databases."""

    name = "browser"
    source_tag = "browser"
    poll_interval = 300

    def __init__(self):
        self._last_check = time.time() - 3600
        self._seen_urls: dict[str, float] = {}
        self._dedup_window_seconds = 24 * 3600

    def poll(self) -> list[tuple[str, dict]]:
        results: list[tuple[str, dict]] = []
        self._prune_seen()
        for entry in self._read_chrome():
            seen_at = self._seen_urls.get(entry["url"])
            if seen_at and (time.time() - seen_at) < self._dedup_window_seconds:
                continue
            self._seen_urls[entry["url"]] = time.time()
            content = f"Visited: {entry['title']}\nURL: {entry['url']}"
            results.append(
                (
                    content,
                    {
                        "url": entry["url"],
                        "title": entry["title"],
                        "browser": "chrome",
                        "content_type": "url",
                    },
                )
            )
        self._last_check = time.time()
        return results

    def _prune_seen(self) -> None:
        now = time.time()
        expired = [u for u, ts in self._seen_urls.items() if (now - ts) > self._dedup_window_seconds]
        for url in expired:
            self._seen_urls.pop(url, None)

    def _read_chrome(self) -> list[dict]:
        system = platform.system()
        if system == "Darwin":
            db_path = Path.home() / "Library/Application Support/Google/Chrome/Default/History"
        elif system == "Linux":
            db_path = Path.home() / ".config/google-chrome/Default/History"
        elif system == "Windows":
            db_path = Path.home() / "AppData/Local/Google/Chrome/User Data/Default/History"
        else:
            return []

        if not db_path.exists():
            return []

        tmp_path: Path | None = None
        try:
            fd, tmp_name = tempfile.mkstemp(suffix=".db")
            os.close(fd)
            tmp_path = Path(tmp_name)
            shutil.copy2(str(db_path), str(tmp_path))
            conn = sqlite3.connect(str(tmp_path))
            conn.row_factory = sqlite3.Row

            chrome_epoch = 11644473600 * 1_000_000
            since = int(self._last_check * 1_000_000) + chrome_epoch

            rows = conn.execute(
                """
                SELECT url, title, last_visit_time FROM urls
                WHERE last_visit_time > ? AND title != ''
                ORDER BY last_visit_time DESC LIMIT 50
                """,
                (since,),
            ).fetchall()
            conn.close()

            return [
                {"url": row["url"], "title": row["title"]}
                for row in rows
                if row["title"] and not row["url"].startswith("chrome://")
            ]
        except Exception:
            return []
        finally:
            if tmp_path:
                tmp_path.unlink(missing_ok=True)
