/**
 * PR Meta Service - Generate PR title and description for code changes
 */

import { z } from 'zod';
import { invokeAgent } from '@zibby/core';
import { adfToText } from '../../../../dist/utils/adf-converter.js';

const PRMetaSchema = z.object({
  prTitle: z.string().describe('Short PR title that includes the ticket key'),
  prDescription: z.string().describe('Markdown description with ## Why and ## How sections with bullet points')
});

/**
 * Generate PR title and description for code changes
 * @param {Object} params
 * @param {Object} params.ticketContext - Ticket info (ticketKey, summary, description)
 * @param {string[]} params.changedFiles - List of changed file paths
 * @param {string} params.diffStat - Git diff statistics
 * @param {Object} params.state - Execution state for invokeAgent
 * @param {string} params.model - AI model to use
 * @returns {Promise<{prTitle: string, prDescription: string}>}
 */
export async function generatePRMeta({ ticketContext, changedFiles, diffStat, state, model }) {
  const prompt = buildPrompt(ticketContext, changedFiles, diffStat);
  const result = await invokeAgent(prompt, { state, model, schema: PRMetaSchema });
  
  // invokeAgent with schema returns { raw, structured } — extract the structured data
  const prMeta = result?.structured || result;
  
  if (!prMeta?.prTitle || !prMeta?.prDescription) {
    throw new Error(`PR meta generation returned incomplete data: ${JSON.stringify(prMeta)}`);
  }

  const prTitle = prMeta.prTitle.includes(ticketContext.ticketKey)
    ? prMeta.prTitle
    : `${ticketContext.ticketKey}: ${prMeta.prTitle}`;
  
  return {
    prTitle,
    prDescription: prMeta.prDescription
  };
}

function buildPrompt(ticketContext, changedFiles, diffStat) {
  // Handle description (could be string or ADF object)
  let descriptionPreview = '';
  if (ticketContext.description) {
    if (typeof ticketContext.description === 'string') {
      descriptionPreview = ticketContext.description.slice(0, 500) + 
        (ticketContext.description.length > 500 ? '...' : '');
    } else if (typeof ticketContext.description === 'object') {
      const converted = adfToText(ticketContext.description);
      descriptionPreview = converted.slice(0, 500) + (converted.length > 500 ? '...' : '');
    }
  }

  return `Generate a pull request title and description for these code changes.

TICKET: ${ticketContext.ticketKey} - ${ticketContext.summary}
${descriptionPreview ? `Description: ${descriptionPreview}\n` : ''}
FILES CHANGED:
${changedFiles.map(f => `  - ${f}`).join('\n')}

DIFF STATS:
\`\`\`
${diffStat}
\`\`\`

Return:
1. prTitle: Short PR title that MUST include "${ticketContext.ticketKey}". Example: "${ticketContext.ticketKey}: Add search collapse animation"

2. prDescription: Markdown with this exact format:
## Why

- Bullet point explaining business/user value
- Another reason for the change

## How

- Bullet point explaining technical approach
- Key files or patterns used

---
*Created by Zibby*`;
}
