import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";

function getLatestScreenshotPath(): { path?: string; error?: string } {
  const home = os.homedir();

  if (process.platform === "darwin") {
    const macPath = path.join(home, "screenshot.png");
    if (fs.existsSync(macPath)) {
      return { path: macPath };
    }
    return { error: `No screenshot found at ${macPath}` };
  }

  const screenshotsDir = path.join(home, "Pictures", "Screenshots");
  if (!fs.existsSync(screenshotsDir)) {
    return { error: `Screenshots directory not found: ${screenshotsDir}` };
  }

  const files = fs
    .readdirSync(screenshotsDir)
    .filter((file) => file.toLowerCase().endsWith(".png"))
    .map((file) => path.join(screenshotsDir, file));

  if (files.length === 0) {
    return { error: `No screenshots found in ${screenshotsDir}` };
  }

  files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
  return { path: files[0] };
}

export default function (pi: ExtensionAPI) {
  pi.registerCommand("shot", {
    description: "Insert the latest screenshot path into the editor",
    handler: async (_args, ctx) => {
      const result = getLatestScreenshotPath();
      if (result.error) {
        ctx.ui.notify(result.error, "error");
        return;
      }
      ctx.ui.setEditorText(result.path!);
      ctx.ui.notify("Inserted latest screenshot path", "info");
    },
  });

  pi.registerTool({
    name: "shot_path",
    label: "Latest screenshot path",
    description: "Get the latest screenshot path for this machine",
    parameters: Type.Object({}),
    async execute() {
      const result = getLatestScreenshotPath();
      if (result.error) {
        return {
          content: [{ type: "text", text: result.error }],
          details: { error: result.error },
        };
      }
      return {
        content: [{ type: "text", text: result.path! }],
        details: { path: result.path },
      };
    },
  });
}
