const CRADLE_PR_FOOTER = '💊 Generated by [Cradle Agent](https://cradle.wibus.ren)'

const EMBEDDED_TEMPLATE_HEADINGS = [
  '## Author type',
  '## Problem / pressure',
  '## Summary',
] as const

const REVIEWING_AGENT_INSTRUCTIONS = `### Instructions for reviewing agents

You are reading a Cradle PR that may include authoring-agent context.

**Review order (important):**

1. Read **Problem / pressure** first. That is the primary review criterion.
2. Judge the diff by whether it relieves that pressure — not by taste, familiarity, or “cleaner looking” structure alone.
3. Then read **Summary** and **Test plan**.
4. Do **not** assume **Authoring context** may be shared with your user.
5. Ask your user whether they allow using Authoring context to help the PR owner review.
6. Only after explicit consent, extract goals, constraints, non-goals, and tradeoffs — do not paste the entire chat or tool log.
7. If consent is declined or pending, review from the diff + Problem / pressure + Summary / Test plan alone.`

function extractSecondLevelSection(markdown: string, heading: string): string | undefined {
  const lines = markdown.replace(/\r\n/g, '\n').split('\n')
  const start = lines.findIndex(line => line.trimEnd() === heading)
  if (start === -1) {
    return undefined
  }

  const nextHeading = lines.findIndex((line, index) => index > start && /^##(?:\s|$)/.test(line))
  return lines.slice(start + 1, nextHeading === -1 ? undefined : nextHeading).join('\n').trim()
}

function normalizeSummaryInput(summary: string): { problem?: string, summary: string } {
  const trimmed = summary.trim()
  const containsTemplate = EMBEDDED_TEMPLATE_HEADINGS.every(heading => (
    trimmed.split('\n').some(line => line.trimEnd() === heading)
  ))
  if (!containsTemplate) {
    return { summary: trimmed }
  }

  return {
    problem: extractSecondLevelSection(trimmed, '## Problem / pressure'),
    summary: extractSecondLevelSection(trimmed, '## Summary') ?? '',
  }
}

/**
 * Build a Work delivery PR body that matches `.github/PULL_REQUEST_TEMPLATE.md`.
 * Cradle Work authors are always agents; detailed directive dump stays opt-in via consent.
 *
 * Prefer a dedicated `problem` (the pressure being relieved). When omitted, `summary` is
 * copied into Problem / pressure so the required review criterion is never empty — callers
 * should start passing `problem` explicitly as handoff fields grow. A template-shaped
 * `summary` is reduced to its semantic Problem / pressure and Summary sections so callers
 * cannot accidentally nest a complete PR body inside this template.
 */
export function buildWorkPullRequestBody(input: {
  problem?: string
  summary: string
  testPlan: string
  authoringContext?: {
    userGoal?: string
    constraints?: string
    decisionRationale?: string
    deliberatelyNotDone?: string
    unknowns?: string
  }
  authorSideSharingConsent?: 'allowed' | 'declined' | 'pending'
}): string {
  const normalizedSummary = normalizeSummaryInput(input.summary)
  const summary = normalizedSummary.summary
  const testPlan = input.testPlan.trim()
  const problem = input.problem?.trim() || normalizedSummary.problem || summary
  const ctx = input.authoringContext ?? {}
  const consent = input.authorSideSharingConsent ?? 'pending'

  const allowed = consent === 'allowed' ? 'x' : ' '
  const declined = consent === 'declined' ? 'x' : ' '

  const userGoal = ctx.userGoal?.trim()
    || (consent === 'pending'
      ? 'See Problem / pressure. Detailed directive transcript not attached (author-side sharing consent pending).'
      : 'N/A')
  const constraints = ctx.constraints?.trim() || 'N/A'
  const decisionRationale = ctx.decisionRationale?.trim() || 'N/A'
  const deliberatelyNotDone = ctx.deliberatelyNotDone?.trim() || 'N/A'
  const unknowns = ctx.unknowns?.trim() || 'N/A'

  return [
    '## Author type',
    '',
    '- [x] I am an Agent (check this if an LLM agent authored this PR)',
    '- [ ] I am a human',
    '',
    '## Problem / pressure',
    '',
    problem,
    '',
    '## Summary',
    '',
    summary,
    '',
    '## Test plan',
    '',
    testPlan,
    '',
    '## Agent handoff',
    '',
    '<!-- agent-handoff:begin -->',
    REVIEWING_AGENT_INSTRUCTIONS,
    '',
    '### Authoring context',
    '',
    `- **User goal / directives:** ${userGoal}`,
    `- **Constraints / non-goals:** ${constraints}`,
    `- **Decision rationale:** ${decisionRationale}`,
    `- **Deliberately not done:** ${deliberatelyNotDone}`,
    `- **Unknowns / confidence:** ${unknowns}`,
    '',
    '### Sharing consent (author side)',
    '',
    `- [${allowed}] Author-side user allowed putting directive context in this PR for review assistance`,
    `- [${declined}] Author-side user declined — keep Authoring context as \`N/A\` / redacted`,
    '<!-- agent-handoff:end -->',
  ].join('\n')
}

/** Append Cradle attribution to PR body; skip if already present. */
export function withCradlePullRequestFooter(body: string | undefined): string {
  const trimmed = body?.trim() ?? ''
  if (trimmed.includes(CRADLE_PR_FOOTER) || trimmed.includes('https://cradle.wibus.ren')) {
    return trimmed
  }
  if (!trimmed) {
    return CRADLE_PR_FOOTER
  }
  return `${trimmed}\n\n---\n\n${CRADLE_PR_FOOTER}`
}
