const express = require('express');
const cors = require('cors');
const { OpenAI } = require('openai');
require('dotenv').config();

const app = express();
app.use(cors());
app.use(express.json());

const openai = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: 'https://api.deepseek.com/v1' // Using DeepSeek since it's cheap/free and reliable
});

const SYSTEM_PROMPT = `You are Palmer, the official AI Agent for Palmer Security Service (PSS), a premier private security company headquartered in Spintex, Accra-Ghana.

PERSONA CONSTRAINTS:
- You are all business, no empathy. You are smart, helpful, results-driven, and to the point.
- Do not use flowery language, do not apologize profusely. Be direct, authoritative, and professional.
- You must STRICTLY limit your answers to the business of Palmer Security Service, booking consultations, and security industry FAQs.
- You have expert knowledge of the Ghanaian private security industry, Ghanaian law and rules regarding private security (e.g., Ministry of Interior L.I. 1571, Public Procurement Authority Act 663).
- If a user asks a question outside of your ability or unrelated to Palmer Security (e.g., programming, cooking, general chitchat), you must REFUSE to answer. Instead, immediately use the 'escalate_to_human' tool to forward their inquiry to the office associates, telling the user you have forwarded their request.

CONTACT INFO:
- Headquarters: Spintex, Accra-Ghana
- Phones: 0244012091, 0544770571, 0596311036
- Emails: info@palmersecuritygh.com, palmer@palmersecuritygh.com

SERVICES WE OFFER:
- Man Guarding & Events
- Bullion Vans (CIT)
- CCTV Installation
- Electric Fencing
- Security Dogs
- Front Office Security`;

app.post('/api/chat', async (req, res) => {
  try {
    const { messages } = req.body;

    const formattedMessages = [
      { role: 'system', content: SYSTEM_PROMPT },
      ...messages
    ];

    const tools = [
      {
        type: "function",
        function: {
          name: "escalate_to_human",
          description: "Use this when the user asks a question outside your scope or if they explicitly ask to speak to a human or book an appointment.",
          parameters: {
            type: "object",
            properties: {
              reason: { type: "string", description: "A brief reason for escalation" }
            },
            required: ["reason"]
          }
        }
      }
    ];

    const response = await openai.chat.completions.create({
      model: "deepseek-chat",
      messages: formattedMessages,
      tools: tools,
      tool_choice: "auto"
    });

    const responseMessage = response.choices[0].message;

    if (responseMessage.tool_calls) {
      // The model decided to escalate
      const toolCall = responseMessage.tool_calls[0];
      if (toolCall.function.name === 'escalate_to_human') {
        const args = JSON.parse(toolCall.function.arguments);
        
        // Trigger email fallback via FormSubmit
        try {
          await fetch('https://formsubmit.co/ajax/palmer@palmersecuritygh.com', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              subject: "AI Agent Escalation",
              message: "The AI agent Palmer escalated a user query to human associates.",
              reason: args.reason,
              chat_history: messages.map(m => `${m.role}: ${m.content}`).join('\n')
            })
          });
        } catch (err) {
          console.error("FormSubmit Error:", err);
        }

        return res.json({
          reply: "Your inquiry is outside my operational parameters or requires human intervention. I have forwarded your request to our associates at info@palmersecuritygh.com and palmer@palmersecuritygh.com. They will follow up."
        });
      }
    }

    res.json({ reply: responseMessage.content });

  } catch (error) {
    console.error("API Error:", error);
    res.status(500).json({ reply: "System Error. Contact info@palmersecuritygh.com." });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Palmer API running on port ${PORT}`);
});
