export interface InstructionSource {
  key: string
  text: string
}

export interface SystemTextPart {
  type: string
  text: string
  metadata?: unknown
}

interface InstructionsMetadata {
  experimental?: { instructions?: unknown }
}

const AGENTS_KEY = "core/instructions"
const DATE_KEY = "core/date"

function instructionSources(system: SystemTextPart[]): { part: SystemTextPart; sources: InstructionSource[] } | undefined {
  for (const part of system) {
    const meta = part.metadata as InstructionsMetadata | undefined
    const sources = meta?.experimental?.instructions
    if (Array.isArray(sources)) {
      return { part, sources: sources as InstructionSource[] }
    }
  }
}

export function insertGuidelines(system: SystemTextPart[], rules: string, rulesPath: string): boolean {
  if (!rules) return false

  const block = `Rules from: ${rulesPath}\n${rules}`
  const found = instructionSources(system)
  if (!found) {
    system.push({ type: "text", text: block })
    return true
  }

  const { part, sources } = found
  const after = sources.find((source) => source.key === AGENTS_KEY)
  // без AGENTS.md источник core/date отмечает место, где он бы стоял
  const before = after ? undefined : sources.find((source) => source.key === DATE_KEY)
  const anchor = after ?? before

  if (anchor && anchor.text) {
    const at = part.text.indexOf(anchor.text)
    if (at >= 0) {
      const cut = after ? at + after.text.length : at
      const insert = after ? "\n\n" + block : block + "\n\n"
      part.text = part.text.slice(0, cut) + insert + part.text.slice(cut)
      return true
    }
  }

  part.text += "\n\n" + block
  return true
}
