const OVERVIEW_PREFIX = '@overview:';

/** 상시업무 단계 — overview + 본문(description)을 한 필드에 저장 */
export function encodeRoutineStageDescription(overview: string, body: string): string | undefined {
  const o = overview.trim();
  const b = body.trim();
  if (!o && !b) return undefined;
  if (!o) return b || undefined;
  return `${OVERVIEW_PREFIX}${o}\n${b}`.trim() || undefined;
}

export function decodeRoutineStageDescription(raw: string | null | undefined): {
  overview: string;
  body: string;
} {
  if (!raw?.trim()) return { overview: '', body: '' };
  if (raw.startsWith(OVERVIEW_PREFIX)) {
    const rest = raw.slice(OVERVIEW_PREFIX.length);
    const nl = rest.indexOf('\n');
    if (nl === -1) return { overview: rest.trim(), body: '' };
    return {
      overview: rest.slice(0, nl).trim(),
      body: rest.slice(nl + 1).trim(),
    };
  }
  return { overview: '', body: raw.trim() };
}

export function parseRoutineContentLines(text: string | null | undefined): string[] {
  if (!text) return [];
  return text
    .split('\n')
    .map((l) => l.replace(/^[•·\-]\s*/, '').trim())
    .filter(Boolean);
}

/** 레거시 @overview: 인코딩 → 편집용 본문 */
export function routineStageBody(raw: string | null | undefined): string {
  if (!raw?.trim()) return '';
  const { overview, body } = decodeRoutineStageDescription(raw);
  if (body) return body;
  return overview;
}
