import type { InitiativeFormState } from './initiativeFormTypes';

/** Same five keys as {@link ReportSection42Key} in `reportApplicationFieldMirror`. */
export type Section42MergeKey = keyof Pick<
  InitiativeFormState,
  'purpose' | 'implementationSteps' | 'firstAppliedUnit' | 'conditions' | 'achievedResult'
>;

/** Labels aligned with báo cáo §4.2 (InitiativeReportForm). */
export const CONTENT_SUMMARY_SECTION_42: ReadonlyArray<{
  key: Section42MergeKey;
  label: string;
}> = [
  { key: 'purpose', label: 'Mục đích (Vấn đề cần giải quyết)' },
  { key: 'implementationSteps', label: 'Các bước thực hiện giải pháp' },
  { key: 'firstAppliedUnit', label: 'Đơn vị áp dụng lần đầu' },
  { key: 'conditions', label: 'Điều kiện cần thiết để áp dụng' },
  { key: 'achievedResult', label: 'Kết quả thu được' },
];

/**
 * Đơn §4 « Nội dung của sáng kiến » — single block built from báo cáo §4.2 fields.
 */
export function formatContentSummaryFromSection42(
  report: Pick<
    InitiativeFormState,
    'purpose' | 'implementationSteps' | 'firstAppliedUnit' | 'conditions' | 'achievedResult'
  >,
): string {
  const blocks: string[] = [];
  for (const { key, label } of CONTENT_SUMMARY_SECTION_42) {
    const value = String(report[key] ?? '').trim();
    if (!value) continue;
    blocks.push(`${label}\n${value}`);
  }
  return blocks.join('\n\n');
}

/**
 * Parses đơn `contentSummary` back into §4.2 scalars. Paragraphs must start with a known heading line.
 * If no headings match, the full string is treated as `purpose`.
 */
export function parseContentSummaryToSection42(
  merged: string,
): Partial<Record<Section42MergeKey, string>> {
  const normalized = merged.replace(/\r\n/g, '\n').trim();
  if (!normalized) {
    return {};
  }

  const chunks = normalized.split(/\n\n+/);
  const out: Partial<Record<Section42MergeKey, string>> = {};
  let matchedAny = false;

  for (const chunk of chunks) {
    const lines = chunk.split('\n');
    const heading = lines[0]?.trim() ?? '';
    const body = lines.slice(1).join('\n').trim();
    const spec = CONTENT_SUMMARY_SECTION_42.find((s) => s.label === heading);
    if (!spec) continue;
    matchedAny = true;
    out[spec.key] = body;
  }

  if (!matchedAny) {
    return { purpose: normalized };
  }
  return out;
}
