import { assertEquals, assert } from "jsr:@std/assert";
import ICAL from "ical.js";
import { expandRecurrences, resolveEventStart, dateToTimezoneString } from "../icalendar.ts";

Deno.test("Integration - parse and expand real-world ICS samples", async () => {
  const testDataDir = "./test_data";
  let files: string[] = [];
  try {
    for await (const dirEntry of Deno.readDir(testDataDir)) {
      if (dirEntry.isFile && dirEntry.name.endsWith(".ics")) {
        files.push(`${testDataDir}/${dirEntry.name}`);
      }
    }
  } catch {
    console.warn("⚠️ No test_data directory found or accessible. Skipping real-data integration test.");
    // We might be running from root
  }

  if (files.length === 0) {
    // Try current dir if test_data is empty (fallback for CI or root execution)
    try {
        for await (const dirEntry of Deno.readDir(".")) {
            if (dirEntry.isFile && dirEntry.name.endsWith(".ics") && dirEntry.name !== "PLUG.md") {
                files.push(dirEntry.name);
            }
        }
    } catch {
        // ignore
    }
  }

  if (files.length === 0) {
    console.warn("⚠️ No .ics files found for integration test.");
    return;
  }

  console.log(`Found ${files.length} files to test.`);

  for (const file of files) {
    console.log(`  Testing file: ${file}`);
    const text = await Deno.readTextFile(file);
    const jcalData = ICAL.parse(text);
    const vcalendar = new ICAL.Component(jcalData);
    const vevents = vcalendar.getAllSubcomponents("vevent");
    
    assert(vevents.length > 0, `Failed to parse ${file} or no events found`);
    
    for (const vevent of vevents) {
      const icsEvent = new ICAL.Event(vevent);
      const status = vevent.getFirstPropertyValue("status") as string | null;
      if (status?.toUpperCase() === "CANCELLED") continue;

      const startDateUTC = icsEvent.startDate.toJSDate();
      const summary = icsEvent.summary;
      const rrule = vevent.getFirstPropertyValue("rrule");
      const exdates = vevent.getAllProperties("exdate").map((p: any) => p.getFirstValue().toJSDate().toISOString());
      
      const localIso = dateToTimezoneString(startDateUTC, "UTC");
      const baseEvent = {
        summary,
        name: summary || "Untitled Event",
        start: startDateUTC.toISOString(),
        startLocal: localIso,
        tag: "ical-event",
        sourceName: "IntegrationTest",
        rrule: rrule ? rrule.toString() : undefined,
        exdate: exdates.length > 0 ? exdates : undefined
      };

      try {
        const expanded = expandRecurrences(baseEvent, 30);
        assert(expanded.length >= 1, `Expected at least 1 occurrence for event "${summary}" in ${file}`);
      } catch (err) {
        console.error(`❌ Error expanding recurrence for event "${summary}" in ${file}:`, err);
        throw err;
      }
    }
  }
});
