#!/bin/zsh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PAYLOAD_DIR="${PAYLOAD_DIR:-$SCRIPT_DIR/portable_payload_arm64}"
INSTALL_ROOT="${INSTALL_ROOT:-$HOME/Library/Application Support/Widgit Print Workaround}"
PDF_SERVICES_DIR="${PDF_SERVICES_DIR:-$HOME/Library/PDF Services}"
PDF_SERVICE_NAME="Widgit Print Workaround.scpt"
TEMP_JS="/tmp/widgit_print_workaround.js"

if [[ ! -x "$PAYLOAD_DIR/bin/pdftocairo" ]]; then
  echo "Missing bundled helper: $PAYLOAD_DIR/bin/pdftocairo"
  exit 1
fi

mkdir -p "$INSTALL_ROOT"
mkdir -p "$PDF_SERVICES_DIR"

# Copy the self-contained helper bundle into the user's Application Support.
ditto "$PAYLOAD_DIR" "$INSTALL_ROOT/portable_payload_arm64"
xattr -dr com.apple.quarantine "$INSTALL_ROOT/portable_payload_arm64" 2>/dev/null || true

INSTALL_ROOT_ESCAPED="${INSTALL_ROOT//\\/\\\\}"
INSTALL_ROOT_ESCAPED="${INSTALL_ROOT_ESCAPED//\"/\\\"}"

cat > "$TEMP_JS" <<EOF
ObjC.import('Foundation');
const installRoot = "${INSTALL_ROOT_ESCAPED}";

function unwrapPath(item) {
  try {
    return ObjC.unwrap(item.toString());
  } catch (error) {}

  try {
    return ObjC.unwrap(item.path());
  } catch (error) {}

  return String(item);
}

function outputPathFor(srcPath) {
  const trimmed = String(srcPath).replace(/\/+$/, "");
  const slash = trimmed.lastIndexOf("/");
  const dir = slash >= 0 ? trimmed.slice(0, slash) : ".";
  const name = slash >= 0 ? trimmed.slice(slash + 1) : trimmed;
  const base = name.replace(/\.pdf$/i, "");
  return dir + "/" + base + "-PRINTSAFE.pdf";
}

function helperPath() {
  return installRoot + "/portable_payload_arm64/bin/pdftocairo";
}

function runCommand(args) {
  const task = $.NSTask.alloc.init;
  const pipe = $.NSPipe.pipe;
  task.setLaunchPath(args[0]);
  task.setArguments(args.slice(1));
  task.setStandardOutput(pipe);
  task.setStandardError(pipe);
  task.launch;
  task.waitUntilExit;

  const data = pipe.fileHandleForReading.readDataToEndOfFile;
  const text = ObjC.unwrap($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding)) || "";
  if (task.terminationStatus !== 0) {
    throw new Error(text || ("Command failed with exit code " + task.terminationStatus));
  }
  return text;
}

function processItem(item) {
  const srcPath = unwrapPath(item);
  if (!srcPath.toLowerCase().endsWith(".pdf")) {
    return;
  }

  const helper = helperPath();
  const dstPath = outputPathFor(srcPath);
  if (!$.NSFileManager.defaultManager.isExecutableFileAtPath(ObjC.wrap(helper))) {
    throw new Error("Bundled converter not found at: " + helper);
  }

  runCommand([helper, "-pdf", srcPath, dstPath]);
  try {
    runCommand(["/usr/bin/open", "-a", "Preview", dstPath]);
  } catch (error) {}
}

function openDocuments(items) {
  for (let i = 0; i < items.length; i += 1) {
    processItem(items[i]);
  }
}

function run(argv) {
  for (let i = 0; i < argv.length; i += 1) {
    processItem(argv[i]);
  }
}
EOF

osacompile -l JavaScript -o "$PDF_SERVICES_DIR/$PDF_SERVICE_NAME" "$TEMP_JS"
xattr -dr com.apple.quarantine "$PDF_SERVICES_DIR/$PDF_SERVICE_NAME" 2>/dev/null || true

echo "Installed:"
echo "  Helper: $INSTALL_ROOT/portable_payload_arm64"
echo "  PDF Service: $PDF_SERVICES_DIR/$PDF_SERVICE_NAME"
