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

/** Subset of báo cáo §5–6 fields that feed Đơn §5 (`authorEvaluation`). */
export type AuthorEvaluationMergeMetricKey = 'economic' | 'teaching' | 'safety' | 'social';

/** Ordered labels must match the báo cáo UI and stay stable for parse/format round-trips. */
export const AUTHOR_EVALUATION_MERGE_SECTIONS: ReadonlyArray<{
  key: 'novelty' | AuthorEvaluationMergeMetricKey;
  label: string;
}> = [
  { key: 'novelty', label: 'Tính mới của sáng kiến' },
  { key: 'economic', label: 'Hiệu quả Kinh tế' },
  { key: 'teaching', label: 'Hiệu quả Công việc/Giảng dạy' },
  { key: 'safety', label: 'Môi trường & An toàn' },
  { key: 'social', label: 'Nhận thức & Xã hội' },
];

type EffectivenessPick = Pick<InitiativeFormState['effectiveness'], AuthorEvaluationMergeMetricKey>;

const EMPTY_METRICS: EffectivenessPick = {
  economic: '',
  teaching: '',
  safety: '',
  social: '',
};

/**
 * Builds Đơn §5 text from báo cáo “Đánh Giá Hiệu Quả” (tính mới + bốn hiệu quả).
 * Empty sections are omitted.
 */
export function formatMergedAuthorEvaluation(
  report: Pick<InitiativeFormState, 'novelty' | 'effectiveness'>,
): string {
  const blocks: string[] = [];
  for (const { key, label } of AUTHOR_EVALUATION_MERGE_SECTIONS) {
    const raw =
      key === 'novelty' ? report.novelty : report.effectiveness[key];
    const value = String(raw ?? '').trim();
    if (!value) continue;
    blocks.push(`${label}\n${value}`);
  }
  return blocks.join('\n\n');
}

/**
 * Parses Đơn §5 text back into báo cáo fields. Paragraphs are split by blank lines;
 * each paragraph must start with a known heading line, or the whole string is treated as `novelty` only.
 */
export function parseMergedAuthorEvaluation(merged: string): {
  novelty: string;
  effectiveness: EffectivenessPick;
} {
  const normalized = merged.replace(/\r\n/g, '\n').trim();
  if (!normalized) {
    return { novelty: '', effectiveness: { ...EMPTY_METRICS } };
  }

  const chunks = normalized.split(/\n\n+/);
  let matchedAny = false;
  const out = {
    novelty: '',
    effectiveness: { ...EMPTY_METRICS },
  };

  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 = AUTHOR_EVALUATION_MERGE_SECTIONS.find((s) => s.label === heading);
    if (!spec) continue;
    matchedAny = true;
    if (spec.key === 'novelty') out.novelty = body;
    else out.effectiveness[spec.key] = body;
  }

  if (!matchedAny) {
    return { novelty: normalized, effectiveness: { ...EMPTY_METRICS } };
  }
  return out;
}
