
import { GoogleGenAI, Type } from "@google/genai";
import { DomainMetrics } from "../types";

export const analyzeDomain = async (domain: string): Promise<DomainMetrics> => {
  const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
  
  const response = await ai.models.generateContent({
    model: 'gemini-3-flash-preview',
    contents: `Analyze the domain "${domain}" and provide an estimated SEO profile. 
    Calculate DA (Domain Authority) and PA (Page Authority). 
    IMPORTANT: Also estimate the DOMAIN AGE (e.g., "12 years, 4 months" or "Est. 2012").
    Provide realistic estimates for spam score, keyword rankings, and technical health based on your knowledge of internet history.`,
    config: {
      responseMimeType: "application/json",
      responseSchema: {
        type: Type.OBJECT,
        properties: {
          domain: { type: Type.STRING },
          da: { type: Type.NUMBER, description: "Domain Authority 1-100" },
          pa: { type: Type.NUMBER, description: "Page Authority 1-100" },
          domainAge: { type: Type.STRING, description: "Estimated age of the domain" },
          spamScore: { type: Type.NUMBER, description: "Spam Score 0-100" },
          totalBacklinks: { type: Type.NUMBER },
          linkingDomains: { type: Type.NUMBER },
          topKeywords: { 
            type: Type.ARRAY,
            items: { type: Type.STRING }
          },
          competitors: { 
            type: Type.ARRAY,
            items: { type: Type.STRING }
          },
          siteHealth: { type: Type.NUMBER, description: "0-100" },
          trustFlow: { type: Type.NUMBER, description: "0-100" },
          citationFlow: { type: Type.NUMBER, description: "0-100" },
          recommendations: { 
            type: Type.ARRAY,
            items: { type: Type.STRING }
          }
        },
        required: ["domain", "da", "pa", "domainAge", "spamScore", "totalBacklinks", "linkingDomains", "siteHealth", "recommendations"]
      },
    },
  });

  try {
    const data = JSON.parse(response.text || "{}");
    return data as DomainMetrics;
  } catch (error) {
    console.error("Failed to parse SEO data", error);
    throw new Error("Gagal menganalisis domain. Silakan coba lagi.");
  }
};
