import { ColorSpecificationSchema, FunctionSpecificationSchema, Lexer, Parser, Interpreter, Config } from './chunk-YBOIEXQ6.js';
import './chunk-MHMD6TZS.js';
import { type } from 'arktype';
import * as readlineSync from 'readline-sync';

var SchemaContentSchema = ColorSpecificationSchema.or(FunctionSpecificationSchema);
var TokenScriptSchemaResponseSchema = type({
  id: "string",
  type: "string",
  schema: "string",
  slug: "string",
  version: "string",
  content: SchemaContentSchema,
  "license_name?": "string | null"
});
async function fetchTokenScriptSchema(schemaUri, options = {}) {
  const { timeout = 1e4, headers = {}, signal } = options;
  const controller = signal ? new AbortController() : new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);
  if (signal) {
    signal.addEventListener("abort", () => controller.abort());
  }
  try {
    const response = await fetch(schemaUri, {
      signal: controller.signal,
      headers: {
        Accept: "application/json",
        "User-Agent": "TokenScript-Interpreter/1.0",
        ...headers
      }
    });
    clearTimeout(timeoutId);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
    }
    const data = await response.json();
    const validatedData = TokenScriptSchemaResponseSchema(data);
    if (validatedData instanceof type.errors) {
      throw new Error(`Invalid schema structure: ${validatedData.summary}`);
    }
    return validatedData;
  } catch (error) {
    clearTimeout(timeoutId);
    if (error instanceof type.errors) {
      throw new Error(`Invalid schema structure: ${error.summary}`);
    }
    if (error instanceof Error) {
      if (error.name === "AbortError") {
        throw new Error(`Schema fetch timeout after ${timeout}ms`);
      }
      throw new Error(`Failed to fetch schema: ${error.message}`);
    }
    throw new Error("Unknown error occurred while fetching schema");
  }
}
async function fetchAndRegisterSchemas(schemaUris, config) {
  const configInstance = config || new Config();
  if (!schemaUris || schemaUris.length === 0) {
    return configInstance;
  }
  const schemas = await Promise.all(
    schemaUris.map(async (uri) => {
      const schemaResponse = await fetchTokenScriptSchema(uri);
      return {
        uri,
        schema: schemaResponse.content
      };
    })
  );
  return configInstance.registerSchemas(schemas);
}
async function startRepl(schemas) {
  console.log("\u{1F680} TokenScript Interactive Mode");
  console.log('Type "exit" or "quit" to exit, "set_variables" to set token references');
  console.log("");
  const config = await fetchAndRegisterSchemas(schemas ?? []);
  let references = {};
  while (true) {
    try {
      const input = readlineSync.question("Enter expression: ");
      if (input.toLowerCase() === "exit" || input.toLowerCase() === "quit") {
        console.log("\u{1F44B} Goodbye!");
        break;
      }
      if (input.toLowerCase() === "set_variables") {
        references = await setVariablesInteractively(references);
        continue;
      }
      if (input.trim() === "") {
        continue;
      }
      const result = await interpretExpression(input, references, config);
      console.log(`\u2705 Result: ${result}`);
    } catch (error) {
      console.error(`\u274C Error: ${error.message}`);
    }
  }
}
async function setVariablesInteractively(currentReferences) {
  const references = { ...currentReferences };
  console.log('\u{1F527} Setting variables (enter "done" to finish):');
  while (true) {
    const input = readlineSync.question('Enter variable (name=value) or "done": ');
    if (input.toLowerCase() === "done") {
      break;
    }
    try {
      const [name, value] = input.split("=").map((s) => s.trim());
      if (!name || value === void 0) {
        console.log("\u26A0\uFE0F  Invalid input. Please enter in the format name=value.");
        continue;
      }
      const numValue = Number.parseFloat(value);
      if (!Number.isNaN(numValue)) {
        references[name] = numValue;
      } else {
        references[name] = value;
      }
      console.log(`\u2705 Set ${name} = ${references[name]}`);
    } catch (_error) {
      console.log("\u26A0\uFE0F  Invalid input. Please enter in the format name=value.");
    }
  }
  return references;
}
async function interpretExpression(code, references, config) {
  try {
    const lexer = new Lexer(code);
    const parser = new Parser(lexer);
    const ast = parser.parse(true);
    if (!ast) {
      return "No result (empty input)";
    }
    const interpreter = new Interpreter(ast, { references, config });
    const result = interpreter.interpret();
    if (result === null) {
      return "null";
    }
    if (typeof result === "string") {
      return result;
    }
    return result.toString();
  } catch (error) {
    throw new Error(`Interpretation failed: ${error.message}`);
  }
}

export { startRepl };
//# sourceMappingURL=repl.js.map
//# sourceMappingURL=repl.js.map