import { ChatGroq } from '@langchain/groq';
import { PromptTemplate } from '@langchain/core/prompts';
import { StringOutputParser } from '@langchain/core/output_parsers';
import { RunnableSequence } from '@langchain/core/runnables';

export interface ContentSignature {
  title: string;
  headings: string;
  metaDesc: string;
  bodyTextSample: string;
  linkCount: number;
  imageCount: number;
  scriptCount: number;
  cssCount: number;
  httpStatus: number;
}

export interface AICheckResult {
  isHacked: boolean;
  confidence: number;
  reason: string;
}

//extract JSON from markdown code blocks
const extractJSON = (text: string): string => {
  // Remove markdown code blocks if present
  const jsonMatch = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
  if (jsonMatch) {
    return jsonMatch[1].trim();
  }
  
  // If no code blocks, try to find JSON object boundaries
  const jsonStart = text.indexOf('{');
  const jsonEnd = text.lastIndexOf('}');
  
  if (jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart) {
    return text.substring(jsonStart, jsonEnd + 1).trim();
  }
  
  // Return original text if no JSON structure found
  return text.trim();
};

export const compareContentWithAI = async (
  currentContent: ContentSignature,
  baselineContent: ContentSignature
): Promise<AICheckResult> => {
  const prompt = `Analyze these website content versions to detect hacking/defacement. Focus on:
- Unexpected content about hacking/defacing
- Drastic content structure changes
- Presence of defacer signatures
- Suspicious content replacements

Baseline Content:
Title: ${baselineContent.title}
Main Headings: ${baselineContent.headings}
Meta Description: ${baselineContent.metaDesc}
Body Sample: ${baselineContent.bodyTextSample}

Current Content:
Title: ${currentContent.title}
Main Headings: ${currentContent.headings}
Meta Description: ${currentContent.metaDesc}
Body Sample: ${currentContent.bodyTextSample}

You must respond with ONLY valid JSON in this exact format (no markdown, no code blocks, no extra text):
{ 
  "isHacked": boolean,
  "confidence": 0-100,
  "reason": "short technical rationale"
}`;

  try {
    const model = new ChatGroq({
      apiKey: process.env.GROQ_API_KEY!,
      model: 'llama-3.1-8b-instant', 
      temperature: 0.2
    });

    // Use a simple prompt template and output parser
    const PROMPT = PromptTemplate.fromTemplate('{question}');
    const chain = RunnableSequence.from([
      {
        question: async () => prompt,
      },
      PROMPT,
      model,
      new StringOutputParser(),
    ]);

    const response = await chain.invoke({});
    
    // Extract JSON from potential markdown formatting
    const cleanedResponse = extractJSON(response);
    
    // Parse the JSON from the model's response
    const result = JSON.parse(cleanedResponse);
    
    // Validate the result structure
    if (typeof result.isHacked !== 'boolean' || 
        typeof result.confidence !== 'number' || 
        typeof result.reason !== 'string') {
      throw new Error('Invalid response structure from AI');
    }
    
    // Ensure confidence is within valid range
    result.confidence = Math.max(0, Math.min(100, result.confidence));
    
    return result;
  } catch (error) {
    console.log('AI analysis failed:', error);
    return {
      isHacked: false,
      confidence: 0,
      reason: 'AI analysis unavailable - fallback to traditional checks',
    };
  }
};