import { getEvolutionContext, recordCreation, getQualityPolicy } from '../evolution.mjs';
import { parseLLMJson } from '../json-utils.mjs';

export const name = 'write-doc';
export const description = 'Write a markdown document (essay, guide, report, story, reference) and save it for the user';

const META_DOC_PATTERN = /\b(loop\s*#?|capabilities?\s+blueprint|delivery\s+protocol|compounding deliverables?|operating model)\b/i;

export async function execute(ctx) {
  const topic = ctx.args?.topic || 'something interesting';
  const growthMode = ctx.args?.growthMode;
  const domain = ctx.args?.domain;
  const connections = ctx.args?.connections || [];
  const goal = ctx.args?.goal || null;
  const userValue = ctx.args?.userValue || '';
  const evidence = Array.isArray(ctx.args?.evidence) ? ctx.args.evidence.map(e => String(e)).filter(Boolean) : [];
  const autonomyMode = ctx.args?._taskSource === 'autonomy';
  const qualityPolicy = getQualityPolicy();
  const minAlignment = Number(qualityPolicy.min_alignment_score) || 70;
  const minUsefulness = Number(qualityPolicy.min_usefulness_score) || 70;

  const evolutionContext = await getEvolutionContext();

  const prompt = `You are an autonomous AI agent and skilled writer.
Write practical, user-facing documents that help someone do real work right now.

${evolutionContext}

${goal ? `Current goal: ${goal}` : ''}
${autonomyMode ? `Autonomy context:
- User value target: ${userValue || '(not provided)'}
- Evidence:
${evidence.length ? evidence.map(e => `  - ${e}`).join('\n') : '  - (none provided)'}
` : ''}

Write a well-structured markdown document about this topic/request:
${topic}

Requirements:
- Use proper markdown formatting (headings, lists, bold, code blocks where appropriate)
- Be thorough but concise - aim for quality over length
- Use a clear, engaging writing style
- Include a title as a top-level heading
- If it's a technical topic, include examples
- Focus on concrete outcomes, checklists, specs, implementation notes, or decision-ready guidance
- Avoid meta/process filler unless explicitly requested
- Do not use titles like "Loop #...", "Capabilities Blueprint", or "Delivery Protocol" unless the topic explicitly asks for them
${autonomyMode ? '- This is autonomous mode: only produce a document if it is directly useful for the user right now.' : ''}

Respond with ONLY the markdown content. Start with a # heading.`;

  let doc = await ctx.askLLM(prompt, { model: ctx.pickModel('analyze') });

  // Strip markdown code fences if Claude wrapped the response
  doc = doc.replace(/^```(?:markdown|md)?\s*\n?/i, '').replace(/\n?\s*```\s*$/, '').trim();
  if (!doc) return 'Skipped writing: empty content.';

  if (autonomyMode) {
    const reviewPrompt = `You are scoring a proposed autonomous deliverable.
Goal: ${goal || '(none)'}
Topic: ${topic}
User value target: ${userValue || '(none)'}
Evidence:
${evidence.length ? evidence.map(e => `- ${e}`).join('\n') : '- (none)'}

Document:
${doc.slice(0, 6000)}

Return JSON only:
{"alignment":0-100,"usefulness":0-100,"generic_meta":true|false,"reason":"short reason"}`;

    const reviewRaw = await ctx.askLLM(reviewPrompt, { model: ctx.pickModel('classify') });
    const reviewParsed = parseLLMJson(reviewRaw);
    const review = reviewParsed.ok ? reviewParsed.data : null;
    const alignment = Number(review?.alignment || 0);
    const usefulness = Number(review?.usefulness || 0);
    const genericMeta = !!review?.generic_meta;
    const topicRequestsMeta = META_DOC_PATTERN.test(String(topic));
    const docLooksMeta = META_DOC_PATTERN.test(doc.slice(0, 400));

    if (!review || alignment < minAlignment || usefulness < minUsefulness || genericMeta || (docLooksMeta && !topicRequestsMeta)) {
      const reason = review?.reason || 'low alignment/usefulness or generic meta output';
      ctx.addEvent('system', 'agent', `Skipped autonomous write-doc: ${reason}`, {
        skill: name,
        alignment,
        usefulness
      });
      return `Skipped writing: ${reason}`;
    }
  }

  // Extract title from first heading for filename
  const titleMatch = doc.match(/^#\s+(.+)/m);
  const title = titleMatch
    ? titleMatch[1].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)
    : `doc-${Date.now()}`;
  const filename = `${title}.md`;

  const written = await ctx.writeOutputFile(filename, doc);
  const actualName = written?.name || filename;

  // Record this creation in the evolution graph
  if (domain) {
    try {
      await recordCreation({
        filename: actualName,
        mode: growthMode || 'branch',
        domain,
        connections
      });
      console.log(`[evolution] Recorded: ${actualName} in domain "${domain}" (${growthMode || 'branch'} mode)`);
    } catch (err) {
      console.log(`[evolution] Failed to record creation: ${err.message}`);
    }
  }

  return `Wrote: ${actualName}`;
}

export default { name, description, execute };

