import { GoogleGenAI, Type, Schema, FunctionDeclaration, GenerateContentResponse } from "@google/genai";
import { SearchPlan } from "../types";

const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });

// --- Tool Definitions (Capabilities) ---

export const searchGoogleSerpTool: FunctionDeclaration = {
  name: "search_google_serp",
  description: "Uses SerpApi to get web results from Google Search.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      query: { type: Type.STRING, description: "The search query string." }
    },
    required: ["query"]
  }
};

export const searchSocialMediaTool: FunctionDeclaration = {
  name: "search_social_media",
  description: "Fetches trending posts and visual trends from social media platforms like TikTok or X.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      query: { type: Type.STRING, description: "The topic or hashtag to search for." },
      platform: { type: Type.STRING, description: "The social media platform (e.g., 'TikTok', 'X')." }
    },
    required: ["query", "platform"]
  }
};

export const searchMarketplacesTool: FunctionDeclaration = {
  name: "search_marketplaces",
  description: "Searches e-commerce platforms like Amazon, Shopify, or Etsy for product listings.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      query: { type: Type.STRING, description: "Product query." },
      category: { type: Type.STRING, description: "Category filter." }
    },
    required: ["query"]
  }
};

export const getAiConsensusTool: FunctionDeclaration = {
  name: "get_ai_consensus",
  description: "Retrieves knowledge and ranking consensus from other Large Language Models regarding the query.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      query: { type: Type.STRING, description: "The entity or topic to retrieve consensus for." },
      model_version: { type: Type.STRING, description: "Specific model to query (e.g., 'gpt-4', 'claude-3', 'gemini-1.5'). Defaults to 'aggregate'." }
    },
    required: ["query"]
  }
};

export const getCompetitorPerformanceTool: FunctionDeclaration = {
  name: "get_competitor_performance",
  description: "Scrapes a competitor's digital footprint (sitemap, social tags) to analyze keyword dominance and market share.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      competitor_url: { type: Type.STRING, description: "The URL of the competitor to analyze." }
    },
    required: ["competitor_url"]
  }
};

const searchPlanSchema: Schema = {
  type: Type.OBJECT,
  properties: {
    query_analysis: {
      type: Type.OBJECT,
      properties: {
        original_query: { type: Type.STRING },
        intent: { type: Type.STRING, enum: ['PRODUCT', 'SERVICE', 'INFORMATIONAL', 'NAVIGATIONAL'] },
        sentiment: { type: Type.STRING },
        complexity_score: { type: Type.NUMBER, description: "0-1 score of query complexity" }
      },
      required: ['original_query', 'intent', 'sentiment', 'complexity_score']
    },
    location_context: {
      type: Type.OBJECT,
      properties: {
        city: { type: Type.STRING },
        country: { type: Type.STRING },
        radius: { type: Type.STRING }
      },
      // Removed nullable: true, treated as optional by exclusion from required list
    },
    target_platforms: {
      type: Type.ARRAY,
      items: { type: Type.STRING },
      description: "e.g., Google, Amazon, TikTok, Instagram, Maps"
    },
    keywords: {
      type: Type.ARRAY,
      items: { type: Type.STRING }
    },
    required_apis: {
      type: Type.ARRAY,
      items: {
        type: Type.OBJECT,
        properties: {
          name: { type: Type.STRING, description: "Name of the tool to use (e.g., search_google_serp)" },
          endpoint: { type: Type.STRING },
          priority: { type: Type.STRING, enum: ['HIGH', 'MEDIUM', 'LOW'] },
          params: { 
            type: Type.OBJECT, 
            properties: {
              q: { type: Type.STRING },
              query: { type: Type.STRING },
              platform: { type: Type.STRING },
              model_version: { type: Type.STRING },
              location: { type: Type.STRING },
              hl: { type: Type.STRING },
              gl: { type: Type.STRING },
              limit: { type: Type.STRING },
              category: { type: Type.STRING },
              competitor_url: { type: Type.STRING }
            },
            // Removed nullable: true, treated as optional
            description: "API parameters matching the tool definition"
          } 
        },
        required: ['name', 'endpoint', 'priority']
      }
    },
    reasoning: { type: Type.STRING, description: "Brief explanation of the search strategy" }
  },
  required: ['query_analysis', 'target_platforms', 'keywords', 'required_apis', 'reasoning']
};

async function retryOperation<T>(operation: () => Promise<T>, retries = 2, delay = 1000, timeoutMs = 60000): Promise<T> {
  for (let i = 0; i < retries; i++) {
    try {
      const timeoutPromise = new Promise<never>((_, reject) => 
        setTimeout(() => reject(new Error("Operation timed out")), timeoutMs)
      );
      return await Promise.race([operation(), timeoutPromise]);
    } catch (error: any) {
      if (i === retries - 1) throw error;
      console.warn(`API Attempt ${i + 1} failed, retrying...`, error);
      await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
    }
  }
  throw new Error("Operation failed after retries");
}

export const generateSearchPlan = async (query: string): Promise<SearchPlan> => {
  // If no API key, we should ideally fail, but for robust demo, we can just log
  // However, the GenAI client throws if no key is provided in constructor or env.
  
  try {
    const response = await retryOperation<GenerateContentResponse>(() => ai.models.generateContent({
      model: 'gemini-3-flash-preview',
      contents: `Analyze this query as the OmniSearch Core Orchestrator: "${query}". 
      
      OBJECTIVE:
      Break this down into a structured JSON search execution plan.

      AVAILABLE TOOLS (Use these names in 'required_apis'):
      - search_google_serp(query)
      - search_social_media(query, platform)
      - search_marketplaces(query, category?)
      - get_ai_consensus(query, model_version?)
      - get_competitor_performance(competitor_url)

      PLATFORM SELECTION RULES:
      1. IF the query involves beauty, fashion, lifestyle, or consumer trends:
         - MUST include "TikTok" (use search_social_media).
      2. IF the query implies a physical location (e.g. "London"):
         - MUST include "Google Maps" (use search_google_serp with 'maps' context or standard maps API).
      3. IF the query is purchase-intent (e.g., "buy", "price", "shop", or specific products):
         - MUST include "Amazon" or "Shopify" (use search_marketplaces).
      4. IF you need general web validation:
         - Use search_google_serp.
      5. IF you need opinion/ranking or comparison:
         - Use get_ai_consensus to see what other AIs think.
      6. IF the query is explicitly asking to analyze a specific competitor URL:
         - Use get_competitor_performance.

      INSTRUCTIONS:
      - Extract any implicit location into 'location_context'.
      - Determine the intent (PRODUCT, SERVICE, etc.).
      - Generate a list of 'required_apis' using the AVAILABLE TOOLS names where possible.
      - Provide a brief 'reasoning' for the platform choices.`,
      config: {
        responseMimeType: "application/json",
        responseSchema: searchPlanSchema,
        systemInstruction: "You are the Master Logic Engine. You analyze vague user queries and turn them into precise, high-performance search strategies. You prefer structured data and technical precision."
      }
    }));

    const text = response.text;
    if (!text) throw new Error("Empty response from Gemini");
    
    return JSON.parse(text) as SearchPlan;
  } catch (error) {
    console.error("Gemini Analysis Failed (Switching to Fallback):", error);
    
    // FALLBACK PLAN (Simulated Intelligence)
    return {
        query_analysis: {
            original_query: query,
            intent: "PRODUCT",
            sentiment: "Positive/Investigative",
            complexity_score: 0.72
        },
        location_context: { city: "London", country: "UK", radius: "10km" },
        target_platforms: ["Google SERP", "TikTok Trends", "Amazon Marketplace", "AI Consensus"],
        keywords: [query, "organic skincare London", "best vegan face cream", "clean beauty UK"],
        required_apis: [
            { name: "search_google_serp", endpoint: "api/v1/serp", priority: "HIGH", params: { query: query } },
            { name: "search_social_media", endpoint: "api/v1/social/tiktok", priority: "MEDIUM", params: { query: query, platform: "TikTok" } },
            { name: "search_marketplaces", endpoint: "api/v1/market/amazon", priority: "HIGH", params: { query: query, category: "Beauty" } }
        ],
        reasoning: "API Connection Unstable: Fallback strategy activated. Prioritizing local SEO and high-intent marketplaces based on query context."
    };
  }
};

export const generateConsensusReport = async (query: string, results: any[]): Promise<string> => {
  try {
    const response = await retryOperation<GenerateContentResponse>(() => ai.models.generateContent({
      model: 'gemini-3-flash-preview',
      contents: `
      CONTEXT:
      The user searched for: "${query}"
      We executed the following tools and got these results:
      ${JSON.stringify(results, null, 2)}

      TASK:
      Take the raw data inputs from the executed tools above.
      Cross-reference them to find the 'Top 3 Consensus Leaders.'
      If a business appears in more than 2 sources, give it a 'SuperApp Verified' badge.
      Generate a 'Visibility Gap' report for 'Brand A'. Specifically analyze where 'Brand A' is present vs. missing compared to the Consensus Leaders.
      
      FORMAT:
      Output a clean Markdown dashboard.
      Include a 'How to Rank Higher' checklist specifically tailored for a business that currently has 0 AI citations (focus on Generative Engine Optimization).
      Use emojis where appropriate for a dashboard feel.
      `,
      config: {
        responseMimeType: "text/plain",
        systemInstruction: "You are the Post-Processing Intelligence Unit. You synthesize fragmented data into executive-level dashboards. You are critical, data-driven, and insightful."
      }
    }));

    return response.text || "Failed to generate report.";
  } catch (error) {
    console.error("Report Generation Failed:", error);
    return "## Analysis Complete (Offline Mode)\n\n**Note:** Live synthesis unavailable. Displaying cached consensus data.\n\n### 🏆 Market Leaders\n- **GlowRecipe** (Viral on TikTok)\n- **The Ordinary** (Search Volume Leader)\n\n### ⚠️ Visibility Gap\nYour brand is missing from 2 key channels: **TikTok** and **Perplexity AI**.";
  }
}

// --- Execution Mock Engine ---

export const executeMockTool = async (toolName: string, params: any) => {
  // Simulate network latency (300-800ms)
  const delay = Math.floor(Math.random() * 500) + 300;
  await new Promise(resolve => setTimeout(resolve, delay));

  // Scenario: Brand A is on Google but NOT TikTok. Brand B is on both.
  const mockEntities = {
    brandA: { name: "Brand A", type: "Established", strength: "SEO" },
    brandB: { name: "GlowRecipe (Brand B)", type: "Viral", strength: "Omnichannel" },
    brandC: { name: "PureSkin (Brand C)", type: "Indie", strength: "Social" }
  };

  if (toolName === 'search_google_serp') {
    return {
      tool: 'search_google_serp',
      timestamp: new Date().toISOString(),
      params: params,
      status: 200,
      data: {
        search_metadata: {
          id: `req_${Math.random().toString(36).substr(2, 9)}`,
          status: "Success",
          json_endpoint: "https://serpapi.com/searches/9823048/65d4.json",
          created_at: new Date().toISOString(),
          processed_at: new Date().toISOString(),
          google_url: `https://www.google.com/search?q=${encodeURIComponent(params.q || params.query || '')}&gl=fr`
        },
        search_parameters: {
          engine: "google",
          q: params.q || params.query,
          location_requested: params.location || "London, UK",
          location_used: "London, Greater London, UK",
        },
        organic_results: [
          {
            position: 1,
            title: `${mockEntities.brandA.name} Official Store | Premium Organics`,
            snippet: "The #1 rated organic skincare for sensitive skin. Dermatologist approved formulas.",
            link: "https://branda.com"
          },
          {
            position: 2,
            title: `${mockEntities.brandB.name} | Fruit-Powered Clinical Skincare`,
            snippet: "Shop our viral Watermelon Glow Sleeping Mask and more. Clean, fruit-forward formulas.",
            link: "https://brandb.com"
          },
          {
            position: 3,
            title: "Top 10 Organic Skincare Brands 2024",
            snippet: `Features industry leaders like ${mockEntities.brandA.name} and the trending ${mockEntities.brandB.name}...`
          }
        ],
        local_results: {
           places: [
             { position: 1, title: mockEntities.brandA.name + " Flagship", rating: 4.8, reviews: 1250, type: "Store", address: "Covent Garden" },
             { position: 2, title: mockEntities.brandB.name + " Pop-up", rating: 4.9, reviews: 8500, type: "Pop-up", address: "Soho" }
           ]
        }
      }
    };
  }

  if (toolName === 'search_social_media') {
     return {
        tool: 'search_social_media',
        platform: params.platform,
        status: 200,
        data: {
           trends: [
              { hashtag: "#SkincareRoutine", views: "12.5B" },
              { hashtag: `#${mockEntities.brandB.name.replace(/\s/g, '').replace(/\(.*\)/, '')}`, views: "850M" } // Brand B is viral
           ],
           top_mentioned_brands: [
             { name: mockEntities.brandB.name, sentiment: "Viral", mentions: "150k+" }, // Brand B
             { name: mockEntities.brandC.name, sentiment: "Rising", mentions: "45k+" }   // Brand C
             // Note: Brand A is deliberately MISSING here to trigger the gap analysis
           ],
           top_posts: [
              { user: "@skincare_junkie", likes: 85000, description: `Omg ${mockEntities.brandB.name} is a game changer! #glow` },
              { user: "@beauty_guru", likes: 42000, description: `Trying out ${mockEntities.brandC.name} today. It's the new dupe!` }
           ]
        }
     }
  }

  if (toolName === 'search_marketplaces') {
    return {
      tool: 'search_marketplaces',
      status: 200,
      data: {
        platform: "Amazon/Shopify",
        top_listings: [
          { title: `${mockEntities.brandB.name} Glow Kit`, price: "$42.00", rating: 4.8, reviews: 12400 },
          { title: "Generic Organic Serum", price: "$18.99", rating: 4.3, reviews: 850 },
          { title: `${mockEntities.brandC.name} Starter Pack`, price: "$29.50", rating: 4.6, reviews: 320 }
        ],
        gap_insight: `${mockEntities.brandA.name} is missing from Top 10 Amazon organic search results for this category.`
      }
    };
  }

  if (toolName === 'get_ai_consensus') {
    return {
      tool: 'get_ai_consensus',
      status: 200,
      model_queried: params.model_version || "AGGREGATE_ENSEMBLE",
      data: {
        consensus_score: 0.72,
        summary: `Analysis shows a significant divergence between search authority and social cultural relevance. ${mockEntities.brandB.name} dominates across all platforms.`,
        market_leaders: [
          { name: mockEntities.brandB.name, status: "Dominant (Omnichannel)" },
          { name: mockEntities.brandA.name, status: "Hidden Entity (0 AI Citations)" }
        ],
        gap_analysis_hint: `CRITICAL: ${mockEntities.brandA.name} appears in traditional search but has 0 citations in LLM knowledge bases. It is effectively invisible to AI-driven discovery.`
      }
    };
  }

  if (toolName === 'get_competitor_performance') {
    return {
        tool: 'get_competitor_performance',
        status: 200,
        competitor_url: params.competitor_url,
        data: {
            market_share: [
                { name: "Your Store", share: 15, color: "bg-emerald-500" },
                { name: "Competitor A", share: 45, color: "bg-red-500" },
                { name: "Competitor B", share: 25, color: "bg-blue-500" },
                { name: "Competitor C", share: 15, color: "bg-amber-500" }
            ],
            winning_keywords: [
                { keyword: "best organic serum", traffic: "12k/mo", owner: "Competitor A" },
                { keyword: "vegan face oil", traffic: "8.5k/mo", owner: "Competitor B" },
                { keyword: "cruelty free toner", traffic: "5k/mo", owner: "Competitor A" }
            ],
            defensive_strategy: {
                immediate_actions: [
                    "Update H1 on 'Rose Mist' page to include 'Vegan' to counter Competitor B.",
                    "Add JSON-LD FAQ schema targeting 'cruelty free' questions."
                ],
                content_gaps: [
                    "Competitor A has a 'Ingredient Glossary' which captures 40% of their top-funnel traffic.",
                    "Missing video comparison content on TikTok."
                ],
                ai_citation_target: "Capture 'best organic serum' snippet on Perplexity by updating product description with data-backed claims."
            }
        }
    }
  }

  return { 
     tool: toolName,
     status: "skipped", 
     message: "Mock implementation pending for this tool.",
     params: params
  };
};