import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

interface AIProviderConfig {
  provider: string;
  apiKey: string;
  model: string;
}

async function getConfiguredProviders(preferredProvider?: string): Promise<AIProviderConfig[]> {
  const providers: AIProviderConfig[] = [];

  try {
    const supabaseUrl = Deno.env.get("SUPABASE_URL");
    const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
    if (!supabaseUrl || !serviceRoleKey) return providers;

    const supabase = createClient(supabaseUrl, serviceRoleKey);
    const { data } = await supabase
      .from("api_configurations")
      .select("provider, config, is_active")
      .eq("provider", "ai")
      .eq("is_active", true)
      .limit(1);

    if (data && data.length > 0) {
      const cfg = (data[0].config || {}) as Record<string, string>;
      const activeProvider = preferredProvider || cfg.provider || "gemini";
      const model = cfg.model || "";

      if (activeProvider.toLowerCase() === "openai") {
        if (cfg.openai_api_key) {
          providers.push({
            provider: "openai",
            apiKey: cfg.openai_api_key,
            model: model.startsWith("openai/") ? model.replace("openai/", "") : "gpt-4o",
          });
        }
        if (cfg.gemini_api_key) {
          providers.push({
            provider: "gemini",
            apiKey: cfg.gemini_api_key,
            model: model.startsWith("google/") ? model.replace("google/", "") : "gemini-2.5-flash",
          });
        }
      } else {
        if (cfg.gemini_api_key) {
          providers.push({
            provider: "gemini",
            apiKey: cfg.gemini_api_key,
            model: model.startsWith("google/") ? model.replace("google/", "") : "gemini-2.5-flash",
          });
        }
        if (cfg.openai_api_key) {
          providers.push({
            provider: "openai",
            apiKey: cfg.openai_api_key,
            model: model.startsWith("openai/") ? model.replace("openai/", "") : "gpt-4o",
          });
        }
      }
    }

    const geminiKey = Deno.env.get("GEMINI_API_KEY");
    if (geminiKey && !providers.find(p => p.provider === "gemini")) {
      providers.push({ provider: "gemini", apiKey: geminiKey, model: "gemini-2.5-flash" });
    }
  } catch (e) {
    console.error("Error fetching AI provider configs:", e);
  }

  return providers;
}

async function callOpenAIStream(apiKey: string, model: string, messages: Array<{ role: string; content: string }>): Promise<Response> {
  const res = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model, messages, stream: true }),
  });

  if (!res.ok) {
    const errText = await res.text();
    throw new Error(`OpenAI ${res.status}: ${errText}`);
  }

  return res;
}

async function callGeminiStream(apiKey: string, model: string, messages: Array<{ role: string; content: string }>): Promise<Response> {
  const systemMsg = messages.find(m => m.role === "system");
  const userMsgs = messages.filter(m => m.role !== "system");

  const contents = userMsgs.map(m => ({
    role: m.role === "assistant" ? "model" : "user",
    parts: [{ text: m.content }],
  }));

  const body: Record<string, unknown> = { contents };
  if (systemMsg) {
    body.systemInstruction = { parts: [{ text: systemMsg.content }] };
  }

  const res = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${apiKey}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    }
  );

  if (!res.ok) {
    const errText = await res.text();
    throw new Error(`Gemini ${res.status}: ${errText}`);
  }

  // Transform Gemini SSE to OpenAI-compatible SSE
  const reader = res.body!.getReader();
  const decoder = new TextDecoder();
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      let buffer = "";
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            controller.enqueue(encoder.encode("data: [DONE]\n\n"));
            controller.close();
            break;
          }

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split("\n");
          buffer = lines.pop() || "";

          for (const line of lines) {
            if (!line.startsWith("data: ")) continue;
            const jsonStr = line.slice(6).trim();
            if (!jsonStr || jsonStr === "[DONE]") continue;

            try {
              const parsed = JSON.parse(jsonStr);
              const text = parsed.candidates?.[0]?.content?.parts?.[0]?.text || "";
              if (text) {
                const chunk = {
                  choices: [{ delta: { content: text }, index: 0, finish_reason: null }],
                };
                controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
              }
            } catch { /* skip */ }
          }
        }
      } catch (e) {
        console.error("Gemini stream error:", e);
        controller.close();
      }
    },
  });

  return new Response(stream, { headers: { "Content-Type": "text/event-stream" } });
}

serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const { message, currentStep, config, conversationHistory, aiProvider } = await req.json();

    if (!message) {
      return new Response(
        JSON.stringify({ error: "message is required" }),
        { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    const systemPrompt = `You are Forge AI, an expert mobile app building assistant. You help users convert websites into native mobile apps.

Current context:
- User is on step ${currentStep} of the app builder
- App name: ${config?.appName || "Not set yet"}
- Website URL: ${config?.websiteUrl || "Not set yet"}

Your role:
- Step 1 (URL Input): Help users choose the right website URL, explain compatibility
- Step 2 (Configure): Explain app settings, navigation styles, features, colors
- Step 3 (Preview): Explain how preview works, troubleshoot display issues
- Step 4 (Build): Explain build process, download options, app store submission

Be helpful, concise, and friendly. Use emojis sparingly. Keep responses under 100 words unless detailed explanation is needed.`;

    const messages: Array<{ role: string; content: string }> = [
      { role: "system", content: systemPrompt },
    ];

    if (conversationHistory && Array.isArray(conversationHistory)) {
      for (const msg of conversationHistory.slice(-6)) {
        if (msg.role && msg.content) {
          messages.push({ role: msg.role, content: msg.content });
        }
      }
    }

    messages.push({ role: "user", content: message });

    let streamResponse: Response | null = null;

    // === Attempt 1: Lovable AI Gateway ===
    const LOVABLE_API_KEY = Deno.env.get("LOVABLE_API_KEY");
    if (LOVABLE_API_KEY) {
      try {
        const model = aiProvider === "openai" ? "openai/gpt-5-mini" : "google/gemini-3-flash-preview";

        const response = await fetch("https://ai.gateway.lovable.dev/v1/chat/completions", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${LOVABLE_API_KEY}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ model, messages, stream: true }),
        });

        if (response.ok) {
          streamResponse = response;
        } else {
          console.warn("Lovable AI Gateway error:", response.status, await response.text());
        }
      } catch (e) {
        console.warn("Lovable AI Gateway unreachable:", e);
      }
    }

    // === Attempt 2: User-configured API keys ===
    if (!streamResponse) {
      console.log("Falling back to user-configured AI providers...");
      const providers = await getConfiguredProviders(aiProvider);

      for (const provider of providers) {
        try {
          console.log(`Trying ${provider.provider} (${provider.model})...`);
          if (provider.provider === "openai") {
            streamResponse = await callOpenAIStream(provider.apiKey, provider.model, messages);
          } else if (provider.provider === "gemini") {
            streamResponse = await callGeminiStream(provider.apiKey, provider.model, messages);
          }
          if (streamResponse) {
            console.log(`Success with ${provider.provider}`);
            break;
          }
        } catch (e) {
          console.warn(`${provider.provider} failed:`, e);
        }
      }
    }

    if (!streamResponse) {
      return new Response(
        JSON.stringify({
          error: "All AI providers failed. Please configure valid API keys in Admin → Integrations, or add Lovable AI credits.",
        }),
        { status: 502, headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    return new Response(streamResponse.body, {
      headers: { ...corsHeaders, "Content-Type": "text/event-stream" },
    });
  } catch (error) {
    console.error("ai-assistant error:", error);
    return new Response(
      JSON.stringify({ error: error instanceof Error ? error.message : "Assistant failed" }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
