import {
  StreamLanguage,
  HighlightStyle,
  syntaxHighlighting,
} from "@codemirror/language";
import { tags } from "@lezer/highlight";

/**
 * CodeMirror 6 syntax highlighting for INI-style config files
 * (Reticulum .conf / NomadNet .conf).
 *
 * Supports: [sections], [[subsections]], key = value, # comments,
 * booleans, numbers, and quoted strings.
 */

const BOOLEANS = new Set([
  "true", "false", "yes", "no", "on", "off", "none",
]);

const iniLanguage = StreamLanguage.define({
  token(stream) {
    // Comments
    if (stream.match(/\s*#/)) {
      stream.skipToEnd();
      return "lineComment";
    }

    // Skip whitespace
    if (stream.eatSpace()) return null;

    // Subsection headers [[name]]
    if (stream.match(/\[\[.*?\]\]/)) return "heading";

    // Section headers [name]
    if (stream.match(/\[.*?\]/)) return "typeName";

    // Quoted strings
    if (stream.match(/"/)) {
      while (!stream.eol()) {
        if (stream.next() === '"') break;
      }
      return "string";
    }

    // Assignment operator
    if (stream.match(/=/)) return "punctuation";

    // Numbers (integers, floats, ports, IPs with dots)
    if (stream.match(/\b\d[\d.]*\b/)) return "number";

    // Words
    if (stream.match(/[\w\-_.]+/)) {
      const word = stream.current().toLowerCase();
      if (BOOLEANS.has(word)) return "atom";
      // Keys appear before '=', values after — both are plain words
      return null;
    }

    stream.next();
    return null;
  },
  startState: () => ({}),
  copyState: (s) => ({ ...s }),
  blankLine: () => {},
  languageData: {},
});

const iniStyle = HighlightStyle.define([
  { tag: tags.typeName, color: "#c792ea", fontWeight: "bold" },   // [section]
  { tag: tags.heading, color: "#82aaff", fontWeight: "bold" },    // [[subsection]]
  { tag: tags.lineComment, color: "#546e7a", fontStyle: "italic" },
  { tag: tags.string, color: "#c3e88d" },
  { tag: tags.number, color: "#f78c6c" },
  { tag: tags.atom, color: "#89ddff" },                           // booleans
  { tag: tags.punctuation, color: "#89ddff" },                    // =
]);

export function iniHighlight() {
  return [iniLanguage, syntaxHighlighting(iniStyle)];
}
