
'use server';
/**
 * @fileOverview Provides an AI-powered chat assistant for Intelli-Wealth Limited.
 *
 * - assistantChat - A function that handles the chat interaction.
 * - AssistantChatInput - The input type for the assistantChat function.
 * - AssistantChatOutput - The return type for the assistantChat function.
 */

import {ai} from '@/ai/genkit';
import {z} from 'genkit';
import { CORE_SERVICES, CONTACT_INFO } from '@/constants'; // KEY_PROJECTS removed
import { getPublicProjects } from '@/lib/actions'; // Import action to fetch projects
import type { Project } from '@/types'; // Import Project type

const AssistantChatInputSchema = z.object({
  userInput: z.string().describe("The user's message to the AI assistant."),
  isInitialGreeting: z.boolean().optional().describe("Indicates if this is the initial interaction to fetch a greeting with suggestions."),
  chatHistory: z.array(z.object({ role: z.enum(['user', 'ai']), content: z.string() })).optional().describe('The history of the conversation so far, excluding the current userInput.'),
});
export type AssistantChatInput = z.infer<typeof AssistantChatInputSchema>;

const AssistantChatOutputSchema = z.object({
  aiResponse: z.string().describe("The AI assistant's response."),
  suggestedReplies: z.array(z.string()).optional().describe('A few short, relevant suggested replies the user can click. Keep these very brief (1-4 words).'),
  whatsAppEscalation: z.object({
    summary: z.string().describe("A concise recap of the user's query so far, written from the USER'S PERSPECTIVE as if they are initiating the WhatsApp message to a human agent (max 40-50 words). For example: \"Hello, I was asking about [topic X] and then had a question about [topic Y]. Could you help me with that?\" This summary will be pre-filled in the WhatsApp message."),
    buttonText: z.string().describe("Text for the WhatsApp escalation button, e.g., 'Chat with a human on WhatsApp'."),
  }).optional().describe("Details for escalating to WhatsApp if offered by the AI."),
});
export type AssistantChatOutput = z.infer<typeof AssistantChatOutputSchema>;

export async function assistantChat(input: AssistantChatInput): Promise<AssistantChatOutput> {
  return assistantChatFlow(input);
}

const prompt = ai.definePrompt({
  name: 'assistantChatPrompt',
  input: {schema: AssistantChatInputSchema.extend({
    // Add context data to the prompt input schema that's not directly from the user
    coreServices: z.any(),
    keyProjects: z.any(), // Will be populated with data from Firestore
    contactInfo: z.any(),
  })},
  output: {schema: AssistantChatOutputSchema},
  prompt: `You are a friendly and helpful AI assistant for Intelli-Wealth Limited.

Your primary goal is to assist users by providing information about Intelli-Wealth Limited, its services, projects, and contact details.
Use the information below and the provided chat history to answer user questions.

About Intelli-Wealth Limited:
Intelli-Wealth Limited is a management consulting firm established in 2016 in Nairobi, Kenya. It specializes in financial inclusion, enterprise development, and experiential marketing across East Africa (Kenya, Uganda, Tanzania, Rwanda).
Key Focus Areas:
- Empowering communities, particularly women and youth.
- Financial literacy programs.
- Agribusiness training.
- Development of innovative digital solutions for transparency and efficiency (e.g., for VSLAs).

Core Services:
{{#each coreServices}}
- {{this.title}}: {{this.descriptionShort}}. Key aspects: {{#each this.detailsShort}}{{{this}}}{{#unless @last}}, {{/unless}}{{/each}}.
{{/each}}

Key Project Examples:
{{#if keyProjects}}
{{#each keyProjects}}
- {{this.title}} (with {{this.organization}}): {{this.descriptionShort}}. Key impacts: {{#each this.impactShort}}{{{this}}}{{#unless @last}}, {{/unless}}{{/each}}.
{{/each}}
{{else}}
(No specific project examples currently available to list, but Intelli-Wealth has worked on various initiatives related to financial inclusion and enterprise development.)
{{/if}}

Contact Information:
- Main Email: {{contactInfo.mainEmail}}
- Main Phone (Kenya, for WhatsApp): {{contactInfo.mainPhone}}
- Website: {{contactInfo.website}}
- Kenya Head Office: {{contactInfo.kenyaHeadOfficeAddress}}, {{contactInfo.kenyaHeadOfficePoBox}}
- Uganda Office: {{contactInfo.ugandaOfficeAddress}}, {{contactInfo.ugandaOfficePoBox}}, Email: {{contactInfo.ugandaOfficeEmail}}, Phone: {{contactInfo.ugandaOfficePhone}}

Your role:
- Answer user questions about Intelli-Wealth Limited in a friendly, concise, and helpful manner.
- Use the chat history (if provided) to understand the context of the ongoing conversation.
- If a question is outside your knowledge or expertise, politely state that you cannot answer it or that it's beyond your current scope. Do not make up information.

{{#if isInitialGreeting}}
Provide a welcoming message and suggest 2-3 common questions the user might ask.
Respond with:
aiResponse: "Hello! I'm the AI assistant for Intelli-Wealth Limited. How can I help you today?"
suggestedReplies: ["What services do you offer?", "Tell me about your projects", "How can I contact Intelli-Wealth?"]
{{else}}
Conversation History:
{{#if chatHistory}}
{{#each chatHistory}}
{{role}}: {{content}}
{{/each}}
{{else}}
(No previous conversation history)
{{/if}}

User's current message: {{{userInput}}}

Respond to the user's message. If your response naturally leads to a few common follow-up questions, or if you ask a question, provide 2-3 very brief (1-4 words) suggestedReplies.

WhatsApp Escalation:
After 2-3 substantive exchanges with the user, OR if the user's query is complex and you feel a human can assist better, OR if the user explicitly asks to speak to a human/representative, you MAY offer to escalate the conversation to a human representative via WhatsApp.
If you decide to offer escalation:
- Include a 'whatsAppEscalation' object in your output.
- This object MUST have two fields:
  1. 'summary': A concise recap of the user's query so far, written from the USER'S PERSPECTIVE as if they are initiating the WhatsApp message to a human agent (max 40-50 words). For example: "Hello, I was asking about [topic X] and then had a question about [topic Y]. Could you help me with that?" This summary will be pre-filled in the WhatsApp message.
  2. 'buttonText': A string for the button, e.g., "Chat with a human on WhatsApp".
- Example for whatsAppEscalation:
  "whatsAppEscalation": {
    "summary": "Hi, I was inquiring about your VSLA digitization services and then asked for details on the CARE International project. Could you please assist further?",
    "buttonText": "Chat with a human on WhatsApp"
  }
- Do NOT offer WhatsApp escalation on the very first or second user message unless the user explicitly asks for human help.
- The WhatsApp number to use for escalation is {{contactInfo.mainPhone}}. Your response should guide the user to click the button you're enabling.
{{/if}}`,
});

const assistantChatFlow = ai.defineFlow(
  {
    name: 'assistantChatFlow',
    inputSchema: AssistantChatInputSchema,
    outputSchema: AssistantChatOutputSchema,
  },
  async (input) => {
    // Fetch recent projects from Firestore
    const fetchedProjects: Project[] = await getPublicProjects(3); // Fetch 3 latest projects
    
    const promptData = {
      ...input,
      coreServices: CORE_SERVICES.map(s => ({
        title: s.title,
        descriptionShort: s.description.substring(0, 100) + (s.description.length > 100 ? '...' : ''), // Keep it brief for the prompt
        detailsShort: s.details.slice(0, 2).map(d => d.substring(0, 50) + (d.length > 50 ? '...' : '')), // First 2 details, shortened
      })),
      keyProjects: fetchedProjects.map(p => ({
        title: p.title,
        organization: p.organization,
        descriptionShort: p.description.substring(0, 100) + (p.description.length > 100 ? '...' : ''), // Keep it brief
        impactShort: p.impact.slice(0, 2).map(i => i.substring(0, 50) + (i.length > 50 ? '...' : '')), // First 2 impacts, shortened
      })),
      contactInfo: {
        mainEmail: CONTACT_INFO.mainEmail,
        mainPhone: CONTACT_INFO.mainPhone,
        website: CONTACT_INFO.website,
        kenyaHeadOfficeAddress: CONTACT_INFO.offices.find(o => o.location.includes("Kenya (Head Office)"))?.addressLines.join(', ') || 'N/A',
        kenyaHeadOfficePoBox: CONTACT_INFO.offices.find(o => o.location.includes("Kenya (Head Office)"))?.poBox || 'N/A',
        ugandaOfficeAddress: CONTACT_INFO.offices.find(o => o.location.includes("Uganda Office"))?.addressLines.join(', ') || 'N/A',
        ugandaOfficePoBox: CONTACT_INFO.offices.find(o => o.location.includes("Uganda Office"))?.poBox || 'N/A',
        ugandaOfficeEmail: CONTACT_INFO.offices.find(o => o.location.includes("Uganda Office"))?.email || 'N/A',
        ugandaOfficePhone: CONTACT_INFO.offices.find(o => o.location.includes("Uganda Office"))?.phone || 'N/A',
      }
    };

    const {output} = await prompt(promptData);
    if (!output) {
      return { aiResponse: "Sorry, I wasn't able to generate a response. Please try again." };
    }
    return output;
  }
);
// The Zod schemas are used internally for defining the prompt and flow.
// Only the async function 'assistantChat' and the TypeScript types 'AssistantChatInput' and 'AssistantChatOutput' are exported.
// This aligns with the requirements for "use server" modules.
