import { getDueReminders, markReminderSent, getEvent } from "./db.js";

const CHANNEL_URL = process.env.ONE_CHANNEL_URL || "http://127.0.0.1:7100";
const CHANNEL_SECRET = process.env.ONE_CHANNEL_SECRET || "";
const NOTIFICATIONS_URL = process.env.NOTIFICATIONS_SERVICE_URL || "http://127.0.0.1:8087";
const POLL_INTERVAL = 60_000; // 60 seconds

function formatLocalTime(isoString: string): string {
  const d = new Date(isoString);
  if (isNaN(d.getTime())) return isoString;
  const tz = process.env.TIMEZONE || "America/New_York";
  return d.toLocaleString("en-US", {
    timeZone: tz,
    weekday: "short",
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
  });
}

async function sendReminderToOne(personName: string, eventTitle: string, eventId: string, startTime: string): Promise<boolean> {
  try {
    const event = getEvent(eventId);
    const location = event?.location ?? "";
    const locLine = location ? `\nLocation: ${location}` : "";
    const displayTime = event?.start_time ? formatLocalTime(event.start_time) : formatLocalTime(startTime);

    const text = `[role: system] Calendar reminder: "${eventTitle}" for ${personName} starts at ${displayTime}.${locLine}\nPlease notify ${personName} about this upcoming appointment.`;

    const res = await fetch(`${CHANNEL_URL}/message`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${CHANNEL_SECRET}`,
      },
      body: JSON.stringify({
        text,
        conversation_id: "system-calendar-reminders",
        user_email: "system:calendar",
      }),
    });

    if (res.ok) {
      const locPart = location ? ` | ${location}` : "";
      fetch(`${NOTIFICATIONS_URL}/notifications`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: `Reminder: ${eventTitle}`,
          description: `${personName} at ${displayTime}${locPart}`,
          source: "calendar",
          level: "info",
        }),
      }).catch(console.error);
    }

    return res.ok;
  } catch (e) {
    console.error(`Failed to send reminder for event ${eventId} to ${personName}:`, e);
    return false;
  }
}

async function processDueReminders(): Promise<void> {
  const due = getDueReminders();
  if (due.length === 0) return;

  console.log(`Processing ${due.length} due reminder(s)`);

  for (const reminder of due) {
    const sent = await sendReminderToOne(
      reminder.person_name,
      reminder.event_title,
      reminder.event_id,
      reminder.remind_at
    );

    if (sent) {
      markReminderSent(reminder.id);
      console.log(`Reminder sent: "${reminder.event_title}" for ${reminder.person_name}`);
    } else {
      console.error(`Failed to send reminder ${reminder.id}, will retry next poll`);
    }
  }
}

let intervalId: ReturnType<typeof setInterval> | null = null;

export function startReminderScheduler(): void {
  console.log("Reminder scheduler started (polling every 60s)");
  processDueReminders().catch(console.error);
  intervalId = setInterval(() => {
    processDueReminders().catch(console.error);
  }, POLL_INTERVAL);
}

export function stopReminderScheduler(): void {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
}
