ObjC.import('stdlib');
ObjC.import('Foundation');

function toAbsolutePath(p) {
  // Expand ~ and make absolute relative to current working directory
  var s = $(String(p)).stringByExpandingTildeInPath;
  if (!s.isAbsolutePath) {
    var cwd = $.NSFileManager.defaultManager.currentDirectoryPath;
    s = cwd.stringByAppendingPathComponent(s);
  }
  return s.stringByStandardizingPath.js;
}

function fileExists(p) {
  return $.NSFileManager.defaultManager.fileExistsAtPath($(p));
}

function getNotes(slide) {
  try { return slide.presenterNotes(); } catch (e) {}
  try { return slide.speakerNotes(); } catch (e) {}
  return "";
}

function run(argv) {
  if (!argv || argv.length < 1) throw new Error("Usage: script.js <file.key> [slides_output_dir]");
  var abs = toAbsolutePath(argv[0]);
  var slidesDir = argv.length >= 2 ? toAbsolutePath(argv[1]) : null;

  if (!fileExists(abs)) {
    throw new Error("File not found: " + abs);
  }

  var Keynote = Application('Keynote');
  Keynote.activate();

  // Keynote is happiest when given a Path() made from an absolute POSIX path
  var doc = Keynote.open(Path(abs));

  // Export slides as PNG if output directory is provided
  if (slidesDir) {
    // Create directory if it doesn't exist
    var fm = $.NSFileManager.defaultManager;
    if (!fm.fileExistsAtPath($(slidesDir))) {
      fm.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(
        $(slidesDir), true, $(), $()
      );
    }

    // Export using AppleScript (more reliable than JXA for Keynote export)
    var app = Application.currentApplication();
    app.includeStandardAdditions = true;

    // Build osascript command with proper escaping
    // Using multiple -e flags to avoid quoting issues
    var cmd = '/usr/bin/osascript' +
      ' -e \'tell application "Keynote"\'' +
      ' -e \'export front document to POSIX file "' + slidesDir + '" as slide images with properties {image format:PNG}\'' +
      ' -e \'end tell\'';

    app.doShellScript(cmd);
  }

  var slides = doc.slides();
  var out = [];
  for (var i = 0; i < slides.length; i++) {
    out.push({
      slide_index: i + 1,
      notes: String(getNotes(slides[i]) || "")
    });
  }

  doc.close({ saving: 'no' });
  return JSON.stringify(out, null, 2);
}
