import nearly from "npm:nearley";
import "./grammar.js";
// deno-lint-ignore no-explicit-any
const grammar = (globalThis as unknown as any)["grammar"];

const compiled_grammar = nearly.Grammar.fromCompiled(grammar);

export type Quality = "x" | "m" | "a" | "s";

export interface Condition {
    quality: Quality;
    cond: "<" | ">";
    value: number;
}

export interface Rule {
    condition: Condition;
    dest: string;
}

export interface Workflow {
    name: string;
    rules: Rule[];
    always: string;
}

export type Material = {
  [key in Quality]: number;
};

interface Input {
    rules: Workflow[];
    materials: Material[];
}

export function parseInput(input: string): Input {
    const parser = new nearly.Parser(compiled_grammar);
    parser.feed(input);
    return parser.results[0];
}