import fs from "fs";
import path from "path";

const vaultRoot = process.env.OBSIDIAN_VAULT_PATH || "/home/garfield/obsidian/vaults";
const cleanupTag = "#squaremcp-test-cleanup";
const pilotLogPath = path.join(vaultRoot, "SquareMCP", "Pilot Requests.md");
const dailyNotePath = path.join(
  vaultRoot,
  "Daily Notes",
  `${new Intl.DateTimeFormat("en-CA", {
    timeZone: "America/New_York",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(new Date())}.md`
);

function removeTaggedBlocks(content) {
  const normalized = content.replace(/\r\n/g, "\n");
  const blocks = normalized.split(/\n{2,}/);
  const kept = blocks.filter((block) => !block.includes(cleanupTag));
  return {
    changed: kept.length !== blocks.length,
    content: kept.join("\n\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n",
    removedCount: blocks.length - kept.length,
  };
}

function cleanFile(filePath) {
  if (!fs.existsSync(filePath)) {
    return { changed: false, removedCount: 0 };
  }

  const original = fs.readFileSync(filePath, "utf8");
  const result = removeTaggedBlocks(original);
  if (result.changed) {
    fs.writeFileSync(filePath, result.content, "utf8");
  }
  return result;
}

const pilotLogResult = cleanFile(pilotLogPath);
const dailyLogResult = cleanFile(dailyNotePath);

console.log("squaremcp cleanup complete");
console.log(`pilot_log_removed: ${pilotLogResult.removedCount}`);
console.log(`daily_log_removed: ${dailyLogResult.removedCount}`);
