// lib/process/stages/package.js — handler for `package` stages.
//
// Final stage. Collects designated prior-stage outputs from the case context,
// renders a cover sheet, and writes a single `case_package` artifact. The
// artifact ID is returned so the engine appends it to the execution's
// artifact_ids list and the UI can link to the package directly.

import { createArtifact } from '../../runtime.js';
import { applyTemplate } from '../template.js';
import { redactSensitiveId } from '../redact.js';

function renderShareholders(shareholders) {
  if (!Array.isArray(shareholders) || shareholders.length === 0) return '_None provided._';
  return shareholders
    .map((s, i) => `${i + 1}. **${s.name || 'Unnamed'}** — ${s.percentage ?? '?'}%`)
    .join('\n');
}

function renderIntakeSection(intake) {
  if (!intake) return '_No intake payload recorded._';
  const lines = [];
  if (intake.applicant_full_name) lines.push(`- **Applicant:** ${intake.applicant_full_name}`);
  if (intake.passport_number) lines.push(`- **Passport (redacted):** ${redactSensitiveId(intake.passport_number)}`);
  if (intake.country_of_residence) lines.push(`- **Country of residence:** ${intake.country_of_residence}`);
  if (intake.email) lines.push(`- **Email:** ${intake.email}`);
  if (intake.proposed_company_name) lines.push(`- **Proposed entity:** ${intake.proposed_company_name}`);
  if (intake.business_activity) lines.push(`- **Business activity:** ${intake.business_activity}`);
  if (intake.share_capital_usd) lines.push(`- **Share capital (USD):** ${intake.share_capital_usd}`);
  if (intake.source_of_funds) lines.push(`\n**Source of funds**\n\n${intake.source_of_funds}`);
  if (intake.shareholders) lines.push(`\n**Shareholders**\n\n${renderShareholders(intake.shareholders)}`);
  return lines.join('\n');
}

function renderJsonSection(label, obj) {
  if (obj == null) return '';
  return `\n\n## ${label}\n\n\`\`\`json\n${JSON.stringify(obj, null, 2)}\n\`\`\``;
}

function renderMoaDraft(intake) {
  const company = intake?.proposed_company_name || 'the Company';
  const shareholders = Array.isArray(intake?.shareholders) ? intake.shareholders : [];
  return [
    `# Memorandum of Association — Draft`,
    ``,
    `**Company:** ${company}`,
    `**Jurisdiction:** Abu Dhabi Global Market (ADGM)`,
    `**Generated:** ${new Date().toISOString()}`,
    ``,
    `## 1. Name`,
    ``,
    `The name of the Company is **${company}**.`,
    ``,
    `## 2. Registered Office`,
    ``,
    `The registered office of the Company shall be situated within the Abu Dhabi Global Market.`,
    ``,
    `## 3. Objects`,
    ``,
    `The objects for which the Company is established are: ${intake?.business_activity || 'general commercial activity'}.`,
    ``,
    `## 4. Share Capital`,
    ``,
    `The authorised share capital of the Company is **USD ${intake?.share_capital_usd || 'TBD'}**.`,
    ``,
    `## 5. Shareholders`,
    ``,
    renderShareholders(shareholders),
    ``,
    `## 6. Liability`,
    ``,
    `The liability of the members is limited.`,
    ``,
    `---`,
    ``,
    `_This document is an advisory draft generated by the Madarx OS process engine in demo mode. Not legal advice._`,
  ].join('\n');
}

export async function executeStage({ case: c, stage }) {
  const config = stage.config || {};
  const intake = c.intake_payload || {};
  const context = c.context || {};

  const title = applyTemplate(config.title_template, { intake, ...context }) ||
    `Case package — ${c.title}`;
  const include = Array.isArray(config.include_stages) && config.include_stages.length > 0
    ? config.include_stages
    : Object.keys(context);

  const lines = [];
  lines.push(`# ${title}`);
  lines.push('');
  lines.push(`**Case:** ${c.title}  `);
  lines.push(`**Case ID:** ${c.id}  `);
  lines.push(`**Definition:** ${c.definition_slug}  `);
  lines.push(`**Generated:** ${new Date().toISOString()}`);
  lines.push('');
  lines.push('## Applicant intake');
  lines.push('');
  lines.push(renderIntakeSection(intake));
  for (const slug of include) {
    if (slug === 'intake') continue; // already rendered
    if (context[slug]) {
      const label = slug.replace(/-/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase());
      lines.push(renderJsonSection(label, context[slug]));
    }
  }

  const summary = lines.join('\n');
  const cover = createArtifact({
    title,
    kind: 'markdown',
    content: summary,
    project_id: c.project_id,
  });

  const artifactIds = [];
  if (cover?.artifact_id) artifactIds.push(cover.artifact_id);

  if (config.attach_moa_draft) {
    const draft = createArtifact({
      title: `MOA draft — ${intake?.proposed_company_name || c.title}`,
      kind: 'markdown',
      content: renderMoaDraft(intake),
      project_id: c.project_id,
    });
    if (draft?.artifact_id) artifactIds.push(draft.artifact_id);
  }

  return {
    kind: 'pass',
    output: {
      package_title: title,
      artifact_ids: artifactIds,
      stages_included: include,
    },
    artifact_ids: artifactIds,
  };
}

export const STAGE_KIND = 'package';
