/**
 * @wrnexus/compiler — the `.wrn` language compiler.
 *
 * Pipeline:  source ──▶ Lexer ──▶ parse() ──▶ AST ──▶ generate() ──▶ TypeScript
 *
 * See VISION.md for the language design. The MVP supports `page` with `state`,
 * `view`, `api`, and `realtime` blocks, lowering to the framework's primitives.
 */

import { parse, ParseError, type PageAst } from "./parser.ts";
import { generate } from "./codegen.ts";
import { generateNative } from "./native-codegen.ts";

export { parse, ParseError } from "./parser.ts";
export { generate } from "./codegen.ts";
export { generateNative, NativeCompileError } from "./native-codegen.ts";
export { Lexer, LexError } from "./tokenizer.ts";
export type {
  PageAst,
  SeoBlock,
  ViewNode,
  Attr,
  StateDecl,
  ApiBlock,
  DataApiBlock,
  DataMode,
  ModeFunctionsBlock,
  RealtimeBlock,
} from "./parser.ts";

export interface CompileResult {
  code: string;
  ast: PageAst;
  diagnostics: string[];
}

/** Compile `.wrn` source into an Expo Router React Native screen. */
export function compileNativeWireFile(source: string): string {
  return generateNative(parse(source));
}

/**
 * Compile `.wrn` source into TypeScript source. Throws `ParseError` on invalid
 * input (the dev loader surfaces this as a readable error page).
 */
export function compileWireFile(source: string): string {
  const ast = parse(source);
  return `// compiled from .wrn\n${generate(ast)}`;
}

/** Richer entry point returning the AST and diagnostics alongside the code. */
export function compile(source: string): CompileResult {
  const diagnostics: string[] = [];
  try {
    const ast = parse(source);
    return { code: `// compiled from .wrn\n${generate(ast)}`, ast, diagnostics };
  } catch (err) {
    if (err instanceof ParseError) diagnostics.push(err.message);
    throw err;
  }
}
