#!/usr/bin/env node

import path from "node:path";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { callPieText } from "./pie_runner.mjs";
import { parseSkillFile } from "./skill_metadata.mjs";

export async function improveDescription({
  skillName,
  skillContent,
  currentDescription,
  evalResults,
  history,
  model,
  testResults = null,
  logDir = null,
  iteration = null,
}) {
  const failedTriggers = evalResults.results.filter((r) => r.should_trigger && !r.pass);
  const falseTriggers = evalResults.results.filter((r) => !r.should_trigger && !r.pass);

  const trainScore = `${evalResults.summary.passed}/${evalResults.summary.total}`;
  const scoresSummary = testResults
    ? `Train: ${trainScore}, Test: ${testResults.summary.passed}/${testResults.summary.total}`
    : `Train: ${trainScore}`;

  let prompt = `You are optimizing a skill description for a Claude Code skill called "${skillName}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.

The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.

Here's the current description:
<current_description>
"${currentDescription}"
</current_description>

Current scores (${scoresSummary}):
<scores_summary>
`;

  if (failedTriggers.length > 0) {
    prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n";
    for (const result of failedTriggers) {
      prompt += `  - "${result.query}" (triggered ${result.triggers}/${result.runs} times)\n`;
    }
    prompt += "\n";
  }

  if (falseTriggers.length > 0) {
    prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n";
    for (const result of falseTriggers) {
      prompt += `  - "${result.query}" (triggered ${result.triggers}/${result.runs} times)\n`;
    }
    prompt += "\n";
  }

  if (history.length > 0) {
    prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n";
    for (const item of history) {
      const trainScoreText = `${item.train_passed ?? item.passed ?? 0}/${item.train_total ?? item.total ?? 0}`;
      const testScoreText = item.test_passed !== undefined && item.test_passed !== null
        ? `${item.test_passed}/${item.test_total}`
        : null;
      prompt += `<attempt train=${trainScoreText}${testScoreText ? `, test=${testScoreText}` : ""}>\n`;
      prompt += `Description: "${item.description}"\n`;
      if (Array.isArray(item.results)) {
        prompt += "Train results:\n";
        for (const result of item.results) {
          prompt += `  [${result.pass ? "PASS" : "FAIL"}] "${String(result.query).slice(0, 80)}" (triggered ${result.triggers}/${result.runs})\n`;
        }
      }
      if (item.note) {
        prompt += `Note: ${item.note}\n`;
      }
      prompt += "</attempt>\n\n";
    }
  }

  prompt += `</scores_summary>

Skill content (for context on what the skill does):
<skill_content>
${skillContent}
</skill_content>

Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:

1. Avoid overfitting
2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.

Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it.

Here are some tips that we've found to work well in writing these descriptions:
- The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does"
- The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.
- The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.
- If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.

I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end.

Please respond with only the new description text in <new_description> tags, nothing else.`;

  const transcript = { iteration, prompt };
  const text = await callPieText(prompt);
  transcript.response = text;

  let description = parseDescription(text);
  transcript.parsed_description = description;
  transcript.char_count = description.length;
  transcript.over_limit = description.length > 1024;

  if (description.length > 1024) {
    const shortenPrompt = `${prompt}

---

A previous attempt produced this description, which at ${description.length} characters is over the 1024-character hard limit:

"${description}"

Rewrite it to be under 1024 characters while keeping the most important trigger words and intent coverage. Respond with only the new description in <new_description> tags.`;
    const shortenText = await callPieText(shortenPrompt);
    const shortened = parseDescription(shortenText);
    transcript.rewrite_prompt = shortenPrompt;
    transcript.rewrite_response = shortenText;
    transcript.rewrite_description = shortened;
    transcript.rewrite_char_count = shortened.length;
    description = shortened;
  }

  transcript.final_description = description;
  if (logDir) {
    await mkdir(logDir, { recursive: true });
    await writeFile(path.join(logDir, `improve_iter_${iteration ?? "unknown"}.json`), JSON.stringify(transcript, null, 2));
  }

  return description;
}

function parseDescription(text) {
  const match = text.match(/<new_description>([\s\S]*?)<\/new_description>/);
  return (match ? match[1] : text).trim().replace(/^"(.*)"$/s, "$1");
}

async function main(argv = process.argv) {
  const args = parseArgs(argv.slice(2));
  const skillPath = path.resolve(args["skill-path"]);
  const evalResults = JSON.parse(await readFile(args["eval-results"], "utf8"));
  const history = args.history ? JSON.parse(await readFile(args.history, "utf8")) : [];
  const { name, content } = await parseSkillFile(skillPath);
  const currentDescription = evalResults.description;

  const description = await improveDescription({
    skillName: name,
    skillContent: content,
    currentDescription,
    evalResults,
    history,
    model: args.model,
  });

  const output = {
    description,
    history: history.concat([{
      description: currentDescription,
      passed: evalResults.summary.passed,
      failed: evalResults.summary.failed,
      total: evalResults.summary.total,
      results: evalResults.results,
    }]),
  };
  process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
}

function parseArgs(args) {
  const flags = {};
  for (let i = 0; i < args.length; i += 1) {
    const value = args[i];
    if (!value.startsWith("--")) continue;
    const key = value.slice(2);
    const next = args[i + 1];
    if (!next || next.startsWith("--")) {
      flags[key] = true;
      continue;
    }
    flags[key] = next;
    i += 1;
  }
  return flags;
}

const entryPath = fileURLToPath(import.meta.url);
if (process.argv[1] && path.resolve(process.argv[1]) === entryPath) {
  main().catch((error) => {
    process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
    process.exitCode = 1;
  });
}
