type RegisterLike = {
  description: string;
  text: string;
  modes: { text: string }[];
};

/** Returns true if a line contains useful register info (not bitfield/access markers) */
export function isInfoLine(line: string): boolean {
  return (
    line.length > 0 &&
    !line.startsWith("//") &&
    !line.startsWith("(R") &&
    !line.startsWith("(W") &&
    !line.startsWith("(R/W") &&
    !line.startsWith("*") &&
    !/^bits?\s+\d/i.test(line)
  );
}

/** Build a single-line summary string for metadata descriptions */
export function buildRegisterSummary(register: RegisterLike): string {
  const trimLine = (line: string) => line.trim();

  const modeLines = register.modes
    .flatMap((mode) => mode.text.split("\n"))
    .map(trimLine)
    .filter(isInfoLine);
  const textLines = register.text.split("\n").map(trimLine).filter(isInfoLine);
  const descriptionLines = register.description.split("\n").map(trimLine).filter(isInfoLine);

  const rawSummary = [...textLines, ...modeLines, ...descriptionLines]
    .join(" ")
    .replace(/\s+/g, " ")
    .trim();

  if (!rawSummary) return "Spectrum Next register details and bit-level behavior.";
  if (rawSummary.length <= 180) return rawSummary;
  return `${rawSummary.slice(0, 177).trimEnd()}...`;
}

/** Build deduplicated summary lines for OG image rendering */
export function buildRegisterSummaryLines(register: RegisterLike): string[] {
  const normalizeLines = (raw: string) => {
    const lines: string[] = [];
    const rawLines = raw.split("\n");
    for (const rawLine of rawLines) {
      const trimmed = rawLine.trim();
      if (!trimmed) {
        if (lines.length > 0 && lines[lines.length - 1] !== "") {
          lines.push("");
        }
        continue;
      }
      if (isInfoLine(trimmed)) {
        lines.push(trimmed);
      }
    }
    return lines;
  };

  const textLines = normalizeLines(register.text);
  const modeLines = register.modes.flatMap((mode) => normalizeLines(mode.text));
  const descriptionLines = normalizeLines(register.description);

  const combined: string[] = [];
  const appendBlock = (block: string[]) => {
    if (block.length === 0) return;
    if (combined.length > 0 && combined[combined.length - 1] !== "") {
      combined.push("");
    }
    combined.push(...block);
  };

  appendBlock(textLines);
  appendBlock(modeLines);
  appendBlock(descriptionLines);

  const deduped: string[] = [];
  const seen = new Set<string>();
  for (const line of combined) {
    if (!line) {
      if (deduped.length > 0 && deduped[deduped.length - 1] !== "") {
        deduped.push("");
      }
      continue;
    }
    if (seen.has(line)) continue;
    seen.add(line);
    deduped.push(line);
  }

  return deduped.length > 0 ? deduped : ["Spectrum Next register details and bit-level behavior."];
}
