// bot/src/fileHeaders.ts — Manages .md file headers
//
// Header format:
//   Card: PROJ-42
//   Tag: #risk-classification
//   ──────────────────────────
//   <content>
//
// idea.md adds a Status field:
//   Card: PROJ-42
//   Tag: #idea
//   Status: /bloqueado
//   ──────────────────────────
//   <content>

import fs from 'node:fs'

export class FileHeaderManager {
  static readonly SEPARATOR = '──────────────────────────'

  static buildHeader(cardId: string, tag: string, status?: string): string {
    const lines: string[] = [
      `Card: ${cardId}`,
      `Tag: ${tag}`,
    ]
    if (status !== undefined) {
      lines.push(`Status: ${status}`)
    }
    lines.push(FileHeaderManager.SEPARATOR)
    return lines.join('\n') + '\n'
  }

  // Writes a file with the header prepended to content
  static writeWithHeader(
    filePath: string,
    cardId: string,
    tag: string,
    content: string,
    status?: string,
  ): void {
    const header = FileHeaderManager.buildHeader(cardId, tag, status)
    fs.writeFileSync(filePath, header + content, 'utf-8')
  }

  // Reads a file and returns parsed header fields + content body
  static parse(
    filePath: string,
  ): { cardId: string; tag: string; status?: string; content: string } | null {
    if (!fs.existsSync(filePath)) return null

    const raw = fs.readFileSync(filePath, 'utf-8')
    const sepIndex = raw.indexOf(FileHeaderManager.SEPARATOR)
    if (sepIndex === -1) return null

    const headerSection = raw.slice(0, sepIndex)
    const content = raw.slice(sepIndex + FileHeaderManager.SEPARATOR.length).replace(/^\n/, '')

    const cardMatch = headerSection.match(/^Card:\s*(.+)$/m)
    const tagMatch = headerSection.match(/^Tag:\s*(.+)$/m)
    const statusMatch = headerSection.match(/^Status:\s*(.+)$/m)

    if (!cardMatch || !tagMatch) return null

    return {
      cardId: cardMatch[1].trim(),
      tag: tagMatch[1].trim(),
      status: statusMatch ? statusMatch[1].trim() : undefined,
      content,
    }
  }

  // Reads only the Status field from idea.md header
  // Returns '/bloqueado' | '/aprovado' | null
  static readStatus(ideaMdPath: string): string | null {
    const parsed = FileHeaderManager.parse(ideaMdPath)
    return parsed?.status ?? null
  }

  // Updates only the Status field in idea.md (preserves all other content)
  static updateStatus(ideaMdPath: string, newStatus: string): void {
    if (!fs.existsSync(ideaMdPath)) {
      throw new Error(`File not found: ${ideaMdPath}`)
    }

    const raw = fs.readFileSync(ideaMdPath, 'utf-8')
    const sepIndex = raw.indexOf(FileHeaderManager.SEPARATOR)
    if (sepIndex === -1) {
      throw new Error(`No separator found in: ${ideaMdPath}`)
    }

    const headerSection = raw.slice(0, sepIndex)
    const afterSep = raw.slice(sepIndex)

    // Replace existing Status line or insert it before the separator
    let updatedHeader: string
    if (/^Status:/m.test(headerSection)) {
      updatedHeader = headerSection.replace(/^Status:.+$/m, `Status: ${newStatus}`)
    } else {
      // Insert Status line just before the separator (i.e., at end of header)
      updatedHeader = headerSection.trimEnd() + `\nStatus: ${newStatus}\n`
    }

    fs.writeFileSync(ideaMdPath, updatedHeader + afterSep, 'utf-8')
  }
}
