import { tool } from "@opencode-ai/plugin";

export default tool({
  description:
    "Refine and optimize a given prompt using the CO-STAR framework (Context, Objective, Style, Tone, Audience, Response). Use this to improve vague or complex user requests before execution.",
  args: {
    prompt: tool.schema.string().describe("The raw prompt to improve"),
    model: tool.schema
      .string()
      .optional()
      .describe("The model to target (default: generic)"),
  },
  execute: async (args: { prompt: string; model?: string }) => {
    const apiKey = process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY;

    if (!apiKey) {
      // Fallback: Return the CO-STAR template if no API key is found
      return `
# CO-STAR Prompt Template
Apply this structure to the prompt: "${args.prompt}"

1. **C (Context):** [Who is asking? What is the background?]
2. **O (Objective):** ${args.prompt}
3. **S (Style):** [Professional, Technical, Creative?]
4. **T (Tone):** [Helpful, Authoritative, Neutral?]
5. **A (Audience):** [Developers, Stakeholders, Users?]
6. **R (Response):** [Format: Code, Markdown, JSON?]

(Tip: Set OPENAI_API_KEY to enable auto-refinement)`;
    }

    // If we have a key, we would ideally call the API.
    // For this implementation, we'll return a meta-prompt that the *calling agent* can use
    // to self-refine if it has the capability, or the user can copy-paste.
    // This avoids adding a heavy fetch dependency if not needed.

    return `
# Refined Prompt Strategy (CO-STAR)

To optimize the request "${args.prompt}", consider these dimensions:

1. **Context:** Define the persona and scenario.
2. **Objective:** "${args.prompt}" (Expand on specific deliverables).
3. **Style/Tone:** Match the target audience (e.g., Technical/Professional).
4. **Response:** Define the exact output format.

**Recommended Action:**
Rewrite the prompt to explicitly include these missing details.
`;
  },
});
