
import { GoogleGenAI } from "@google/genai";

const SYSTEM_INSTRUCTION = `You are the primary AI Technical Consultant for "Hanmo Control & Network Co., Ltd.". 
Hanmo is a global leader specializing in:
1. DCS (Distributed Control Systems): High-availability process automation for utility-scale industries.
2. SCADA (Supervisory Control and Data Acquisition): Real-time remote operations and monitoring.
3. Database & Historian Servers: Secure, high-speed industrial data management.
4. Precision Control Instruments: Smart sensors and actuators for flow, pressure, and thermal management.

Tone: Professional, highly technical, authoritative, and helpful. 
Language: You must respond in English at all times.
Guidance: Provide expert advice on automation architecture and integration. For pricing or project-specific quotes, instruct the user to use the official contact form on the website.`;

export async function chatWithExpert(message: string, history: {role: 'user' | 'model', text: string}[]) {
  try {
    const ai = new GoogleGenAI({ apiKey: process.env.API_KEY || '' });
    
    const response = await ai.models.generateContent({
      model: 'gemini-3-flash-preview',
      contents: [
        ...history.map(h => ({ role: h.role === 'user' ? 'user' : 'model', parts: [{ text: h.text }] })),
        { role: 'user', parts: [{ text: message }] }
      ],
      config: {
        systemInstruction: SYSTEM_INSTRUCTION,
        temperature: 0.7,
      },
    });

    return response.text || "I apologize, but I am unable to process your technical inquiry right now. Please try again later.";
  } catch (error) {
    console.error("Gemini API Error:", error);
    return "Our technical advisor is currently offline. Please contact our support team directly via email.";
  }
}
