// Calendar CORE (read) — the MCP/terminal reads the same calendar the UI shows. The Swift app mirrors
// macOS Calendar.app (EventKit) into the `calendar_event` table on each refresh; this reads that mirror.
// Pure read. Creating events stays in the app (EventKit is Swift-only) until the engine-command queue lands.

import type { DatabaseSync } from "node:sqlite";
import { selectedWorkspaceId } from "./sync/workspace.ts";

/// Upcoming events from the mirror, within the next `days` (default 14). Past-but-not-ended kept.
export function calendarEvents(db: DatabaseSync, a?: { days?: number; limit?: number }) {
  // Table may not exist yet (app not launched since the calendar build) — guard.
  try {
    db.prepare(`SELECT 1 FROM calendar_event LIMIT 1`).get();
  } catch {
    return { ok: false, events: [], note: "No calendar mirror yet — open DewLink and connect your calendar (GTM → Meetings) so events sync to the local DB." };
  }
  const days = a?.days ?? 14;
  const limit = a?.limit ?? 100;
  const nowMs = Date.now();
  const horizon = nowMs + days * 24 * 3600 * 1000;
  const ws = selectedWorkspaceId(db);
  const hasAttendeeDetails = hasColumn(db, "calendar_event", "attendees_json");
  const rows = db.prepare(
    `SELECT id, title, start_ms, end_ms, all_day, calendar, location, attendees${hasAttendeeDetails ? ", attendees_json" : ""}
     FROM calendar_event WHERE workspace_id=? AND end_ms >= ? AND start_ms <= ?
     ORDER BY start_ms ASC LIMIT ?`).all(ws, nowMs - 3600_000, horizon, limit) as any[];
  const events = rows.map((r) => ({
    id: r.id, title: r.title,
    start: new Date(r.start_ms).toISOString(), end: new Date(r.end_ms).toISOString(),
    all_day: !!r.all_day, calendar: r.calendar, location: r.location || "",
    attendees: r.attendees,
    attendee_details: hasAttendeeDetails ? safeArray(r.attendees_json) : [],
    starts_in_min: Math.round((r.start_ms - nowMs) / 60000),
  }));
  return { ok: true, count: events.length, window_days: days, events };
}

function hasColumn(db: DatabaseSync, table: string, column: string): boolean {
  try {
    return (db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some((c) => c.name === column);
  } catch {
    return false;
  }
}

function safeArray(value: unknown): unknown[] {
  try {
    const parsed = JSON.parse(String(value ?? "[]"));
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}
