"""Calendar ingestion sensor (ICS/local export based)."""

from __future__ import annotations

import re
import time
from pathlib import Path

from neurovault.sensors.base import BaseSensor


class CalendarSensor(BaseSensor):
    """Read local ICS calendar exports and ingest recent/upcoming events."""

    name = "calendar"
    source_tag = "calendar"
    poll_interval = 900.0

    def __init__(self, watch_paths: list[str] | None = None):
        self._watch_paths = watch_paths or [str(Path.home() / "Calendar")]
        self._seen: set[str] = set()

    def poll(self) -> list[tuple[str, dict]]:
        events: list[tuple[str, dict]] = []
        for base in self._watch_paths:
            root = Path(base).expanduser()
            if not root.exists():
                continue
            for ics_path in root.rglob("*.ics"):
                events.extend(self._read_ics(ics_path))
        return events

    def _read_ics(self, path: Path) -> list[tuple[str, dict]]:
        key = f"{path}:{path.stat().st_mtime_ns}"
        if key in self._seen:
            return []
        self._seen.add(key)

        try:
            text = path.read_text(errors="ignore")
        except Exception:
            return []

        blocks = text.split("BEGIN:VEVENT")
        results: list[tuple[str, dict]] = []
        now = int(time.time())

        for block in blocks[1:]:
            summary = _extract_field(block, "SUMMARY")
            dtstart = _extract_field(block, "DTSTART")
            location = _extract_field(block, "LOCATION")
            description = _extract_field(block, "DESCRIPTION")
            if not summary:
                continue

            content = f"Calendar event: {summary}"
            if location:
                content += f"\nLocation: {location}"
            if description:
                content += f"\nDetails: {description[:300]}"
            if dtstart:
                content += f"\nStart: {dtstart}"

            results.append(
                (
                    content,
                    {
                        "content_type": "calendar_event",
                        "source_file": str(path),
                        "event_start": dtstart,
                        "captured_at": now,
                    },
                )
            )
        return results


def _extract_field(block: str, field_name: str) -> str:
    pattern = re.compile(rf"{re.escape(field_name)}[^:]*:(.+)")
    match = pattern.search(block)
    if not match:
        return ""
    return match.group(1).strip()
