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(): 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 = (cfg.provider || "gemini").toLowerCase();
      const model = cfg.model || "";

      // Add the active provider first, then the other one as fallback
      if (activeProvider === "openai" || activeProvider !== "gemini") {
        if (cfg.openai_api_key) {
          providers.push({
            provider: "openai",
            apiKey: cfg.openai_api_key,
            model: model.startsWith("openai/") ? model : "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 : "gpt-4o",
          });
        }
      }
    }

    // Also check individual secrets as additional fallback
    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 callOpenAI(apiKey: string, model: string, messages: Array<{ role: string; content: string }>): Promise<string> {
  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, temperature: 0.7, max_tokens: 1000 }),
  });

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

  const data = await res.json();
  return data.choices?.[0]?.message?.content || "";
}

async function callGemini(apiKey: string, model: string, messages: Array<{ role: string; content: string }>): Promise<string> {
  // Convert messages to Gemini format
  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 }] };
  }
  body.generationConfig = { temperature: 0.7, maxOutputTokens: 1000 };

  const res = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?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}`);
  }

  const data = await res.json();
  return data.candidates?.[0]?.content?.parts?.[0]?.text || "";
}

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

  try {
    const { websiteUrl } = await req.json();

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

    let domain = "";
    try {
      const url = new URL(websiteUrl);
      domain = url.hostname.replace(/^www\./, "");
    } catch {
      domain = websiteUrl;
    }

    console.log("Analyzing website:", websiteUrl);

    const systemPrompt = `You are an expert mobile app designer and UX analyst. Analyze the given website URL and suggest optimal mobile app configuration settings.

Based on the website domain and typical patterns for such sites, provide intelligent suggestions for converting it into a mobile app.

You must respond with a JSON object containing these fields:
- app_name: A clean, mobile-friendly app name derived from the website (max 20 chars)
- primary_color: A hex color code that would match the website's brand (e.g., "#3B82F6")
- accent_color: A complementary hex accent color (e.g., "#8B5CF6")
- navigation_style: One of "bottom-nav", "drawer", or "tabs" - choose based on content type
- features: An array of 3-6 relevant features like ["offline_mode", "push_notifications", "dark_mode", "share", "favorites", "search"]
- app_category: Category like "news", "shopping", "social", "business", "education", "entertainment", "lifestyle", "utility"
- description: A one-sentence app description (max 100 chars)
- icon_style: One of "modern", "classic", "minimal", "rounded", "gradient"
- splash_screen_style: One of "centered-logo", "full-bleed", "minimal", "animated"

Respond ONLY with valid JSON, no markdown or explanations.`;

    const userPrompt = `Analyze this website and suggest mobile app settings: ${websiteUrl}\n\nDomain: ${domain}\n\nProvide your analysis as a JSON object.`;

    const messages = [
      { role: "system", content: systemPrompt },
      { role: "user", content: userPrompt },
    ];

    let content = "";
    let aiSuccess = false;

    // === Attempt 1: Lovable AI Gateway ===
    const LOVABLE_API_KEY = Deno.env.get("LOVABLE_API_KEY");
    if (LOVABLE_API_KEY) {
      try {
        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: "google/gemini-3-flash-preview",
            messages,
            temperature: 0.7,
            max_tokens: 1000,
          }),
        });

        if (response.ok) {
          const aiResponse = await response.json();
          content = aiResponse.choices?.[0]?.message?.content || "";
          if (content) aiSuccess = true;
        } 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 (OpenAI / Gemini) ===
    if (!aiSuccess) {
      console.log("Falling back to user-configured AI providers...");
      const providers = await getConfiguredProviders();

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

    if (!aiSuccess || !content) {
      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" } }
      );
    }

    // Parse the JSON from AI response
    let config;
    try {
      let jsonStr = content.trim();
      if (jsonStr.startsWith("```json")) jsonStr = jsonStr.slice(7);
      else if (jsonStr.startsWith("```")) jsonStr = jsonStr.slice(3);
      if (jsonStr.endsWith("```")) jsonStr = jsonStr.slice(0, -3);
      jsonStr = jsonStr.trim();
      config = JSON.parse(jsonStr);
    } catch {
      console.error("Failed to parse AI response:", content);
      config = {
        app_name: domain.split(".")[0].charAt(0).toUpperCase() + domain.split(".")[0].slice(1),
        primary_color: "#3B82F6",
        accent_color: "#8B5CF6",
        navigation_style: "bottom-nav",
        features: ["offline_mode", "push_notifications", "dark_mode"],
        app_category: "utility",
        description: `Mobile app for ${domain}`,
        icon_style: "modern",
        splash_screen_style: "centered-logo",
      };
    }

    console.log("Analysis successful for:", domain);

    return new Response(
      JSON.stringify({ config }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  } catch (error) {
    console.error("analyze-website error:", error);
    return new Response(
      JSON.stringify({ error: error instanceof Error ? error.message : "Analysis failed" }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
