import { loadDesignEngineer } from "./component-discovery.js";
import { L as LLMClient, s as stepCountIs, l as listComponentsTool, g as getComponentInfoTool } from "../component-tools-DSuKjvQo.js";
import { composeScreenPlan } from "./compose-screen-plan.js";
const screenGenerator = async ({
  prompt,
  schema,
  model,
  planningModel
}) => {
  const plan = await generatePlan(
    prompt,
    schema,
    planningModel || "gpt-5-nano"
  );
  const { response, prompt: designEngineerPrompt } = await generateCode(plan, schema, model) || {};
  const codeWithoutCodeFences = response ? checkAndRemoveCodeFences(response) : null;
  return {
    prompt,
    schema,
    plan,
    designEngineerPrompt,
    code: codeWithoutCodeFences || `
  import { ScreenWrapper } from "@glide/glide-ui/chrome";
  export default function YourScreen() {
    return (
      <ScreenWrapper>
        <div>Your screen content</div>
      </ScreenWrapper>
    );
  }
  `
  };
};
const checkAndRemoveCodeFences = (text) => {
  if (!text) {
    return null;
  }
  let cleaned = text.trim();
  const importIndex = cleaned.indexOf("import");
  if (importIndex === -1) {
    return cleaned;
  }
  cleaned = cleaned.substring(importIndex);
  const lastClosingMatch = cleaned.match(/\);[\s\n]*$/);
  if (lastClosingMatch) {
    const endIndex = lastClosingMatch.index + 2;
    cleaned = cleaned.substring(0, endIndex);
  }
  return cleaned.trim();
};
const generateCode = async (plan, schema, model) => {
  if (!plan) {
    return null;
  }
  const template = loadDesignEngineer();
  let prompt = template.replace("{{PLAN}}", plan);
  prompt = schema ? prompt.replace("{{SCHEMA}}", schema) : prompt.replace("{{SCHEMA}}", "");
  const llmClient = new LLMClient();
  await llmClient.initialize();
  const response = await llmClient.generate(
    { prompt },
    {
      model,
      maxTokens: 25e3,
      tools: {
        get_component_info: getComponentInfoTool
      },
      stopWhen: stepCountIs(2)
    }
  );
  return { response, prompt };
};
const generatePlan = async (prompt, schema, model) => {
  const llmClient = new LLMClient();
  await llmClient.initialize();
  const designEngineerPrompt = composeScreenPlan(prompt, schema);
  const response = await llmClient.generate(
    { prompt: designEngineerPrompt },
    {
      model,
      maxTokens: 8e3,
      tools: {
        list_components: listComponentsTool
      },
      stopWhen: stepCountIs(2)
    }
  );
  return response;
};
export {
  screenGenerator
};
