import type { Attrs } from "./types"

/**
 * Parse a `{key="value" .class #id boolflag}` string into an Attrs object.
 *
 * Grammar (per comark spec):
 *   Attrs  ::= (KeyValue | Class | Id | Bool)*
 *   KeyValue ::= word "=" JSONString
 *   Class    ::= "." word
 *   Id       ::= "#" word
 *   Bool     ::= word
 */
export function parseAttrs(input: string): Attrs {
  const attrs: Attrs = {}
  const re = /(:?[\w-]+)="([^"]*)"|\.([\w-]+)|#([\w-]+)|(\b[\w-]+\b)/g
  let match: RegExpExecArray | null

  while ((match = re.exec(input)) !== null) {
    if (match[1] !== undefined) {
      // key="value"
      attrs[match[1]] = match[2]
    } else if (match[3] !== undefined) {
      // .class-name
      const cls = match[3]
      attrs.class = attrs.class ? `${attrs.class} ${cls}` : cls
    } else if (match[4] !== undefined) {
      // #id
      attrs.id = match[4]
    } else if (match[5] !== undefined) {
      // bool flag
      attrs[match[5]] = true
    }
  }

  return attrs
}
