/**
 * Review Questions AI Service
 * Generates industry-specific bilingual review questions using OpenRouter AI
 *
 * @module lib/services/review-questions.service
 */

import { openRouterService } from '@/lib/services/openrouter.service';
import { convexQuery, convexMutation } from '@/lib/convex-client';
import { logger } from '@/lib/logger';

const log = logger.scope('ReviewQuestionsService');

const QUESTION_MODEL = 'qwen/qwen3-30b-a3b';

interface ReviewQuestion {
  questionEn: string;
  questionAr: string;
}

interface ConvexQuestionTemplate {
  _id: string;
  prismaId?: string;
  userId: string;
  industry: string;
  questions: ReviewQuestion[];
  isDefault: boolean;
  createdAt: number;
  updatedAt: number;
}

function mapTemplate(t: ConvexQuestionTemplate): {
  id: string;
  userId: string;
  industry: string;
  questions: ReviewQuestion[];
  isDefault: boolean;
  createdAt: Date;
  updatedAt: Date;
} {
  return {
    id: t.prismaId ?? t._id,
    userId: t.userId,
    industry: t.industry,
    questions: (t.questions ?? []) as ReviewQuestion[],
    isDefault: t.isDefault,
    createdAt: new Date(t.createdAt),
    updatedAt: new Date(t.updatedAt),
  };
}

const DEFAULT_QUESTIONS: Record<string, ReviewQuestion[]> = {
  healthcare: [
    { questionEn: 'How would you rate the quality of care you received?', questionAr: 'كيف تقيّم جودة الرعاية التي حصلت عليها؟' },
    { questionEn: 'Was the staff friendly and professional?', questionAr: 'هل كان الموظفون ودودين ومحترفين؟' },
    { questionEn: 'How was the cleanliness of the facility?', questionAr: 'كيف كانت نظافة المنشأة؟' },
    { questionEn: 'Were you seen within a reasonable wait time?', questionAr: 'هل تمت رؤيتك خلال وقت انتظار معقول؟' },
    { questionEn: 'Would you recommend this clinic to others?', questionAr: 'هل تنصح الآخرين بهذه العيادة؟' },
  ],
  beauty: [
    { questionEn: 'How satisfied were you with the result?', questionAr: 'ما مدى رضاك عن النتيجة؟' },
    { questionEn: 'Was the salon clean and comfortable?', questionAr: 'هل كان الصالون نظيفًا ومريحًا؟' },
    { questionEn: 'Did the stylist listen to your preferences?', questionAr: 'هل استمع المصمم لتفضيلاتك؟' },
    { questionEn: 'How was the overall atmosphere?', questionAr: 'كيف كان الجو العام؟' },
    { questionEn: 'Would you book with us again?', questionAr: 'هل ستحجز معنا مرة أخرى؟' },
  ],
  restaurant: [
    { questionEn: 'How would you rate the food quality?', questionAr: 'كيف تقيّم جودة الطعام؟' },
    { questionEn: 'Was the service prompt and courteous?', questionAr: 'هل كانت الخدمة سريعة ومهذبة؟' },
    { questionEn: 'How was the ambiance and cleanliness?', questionAr: 'كيف كان الجو والنظافة؟' },
    { questionEn: 'Was the menu variety satisfactory?', questionAr: 'هل كان تنوع القائمة مُرضيًا؟' },
    { questionEn: 'Would you dine with us again?', questionAr: 'هل ستتناول الطعام معنا مرة أخرى؟' },
  ],
  legal: [
    { questionEn: 'How well did the lawyer explain your case?', questionAr: 'ما مدى وضوح شرح المحامي لقضيتك؟' },
    { questionEn: 'Were you kept informed throughout the process?', questionAr: 'هل تم إبلاغك بالمستجدات طوال العملية؟' },
    { questionEn: 'Was the consultation professional and thorough?', questionAr: 'هل كانت الاستشارة مهنية وشاملة؟' },
    { questionEn: 'How would you rate the value for the fees paid?', questionAr: 'كيف تقيّم القيمة مقابل الرسوم المدفوعة؟' },
    { questionEn: 'Would you recommend this firm to others?', questionAr: 'هل تنصح الآخرين بهذا المكتب؟' },
  ],
  'real-estate': [
    { questionEn: 'How responsive was your agent to your inquiries?', questionAr: 'ما مدى استجابة وكيلك لاستفساراتك؟' },
    { questionEn: 'Did the property match what was described?', questionAr: 'هل تطابق العقار مع ما تم وصفه؟' },
    { questionEn: 'Was the viewing process well organized?', questionAr: 'هل كانت عملية المعاينة منظمة بشكل جيد؟' },
    { questionEn: 'How transparent was the agent about pricing and terms?', questionAr: 'ما مدى شفافية الوكيل بشأن الأسعار والشروط؟' },
    { questionEn: 'Would you use this agency again?', questionAr: 'هل ستستخدم هذه الوكالة مرة أخرى؟' },
  ],
  general: [
    { questionEn: 'How would you rate your overall experience?', questionAr: 'كيف تقيّم تجربتك بشكل عام؟' },
    { questionEn: 'Was the staff helpful and professional?', questionAr: 'هل كان الموظفون مفيدين ومحترفين؟' },
    { questionEn: 'How easy was it to book your appointment?', questionAr: 'ما مدى سهولة حجز موعدك؟' },
    { questionEn: 'Did the service meet your expectations?', questionAr: 'هل لبّت الخدمة توقعاتك؟' },
    { questionEn: 'Would you recommend us to friends and family?', questionAr: 'هل تنصح أصدقاءك وعائلتك بنا؟' },
  ],
};

/**
 * Generate bilingual review questions using OpenRouter AI (qwen/qwen3-30b-a3b).
 * The AI analyzes the specific industry to create questions that yield
 * actionable feedback the business can use to improve operations and grow.
 * Falls back to curated defaults when AI is unavailable.
 */
export async function generateReviewQuestions(
  industry: string,
  language: 'en' | 'ar',
  count: number
): Promise<ReviewQuestion[]> {
  if (!openRouterService.isConfigured()) {
    log.info('OpenRouter not configured, using default questions', { industry });
    return getDefaultQuestions(industry, count);
  }

  const langLabel = language === 'ar' ? 'Arabic' : 'English';
  const industryLabel = industry === 'general' ? 'service-based' : industry;

  const systemPrompt = `You are an expert in customer experience and business feedback for service-based businesses in the GCC region (Qatar, Saudi Arabia, UAE, Kuwait, Bahrain, Oman).

Your task is to generate review questions that will produce ACTIONABLE feedback — the kind that helps a business owner identify what to improve, what to double down on, and what drives customer loyalty.

Think about what matters most for a ${industryLabel} business:
- What are the key moments in the customer journey?
- What operational aspects directly affect repeat business?
- What differentiates excellent service from average in this industry?
- What feedback would help the owner make concrete improvements?

Do NOT generate generic "rate your experience" questions. Each question should target a specific, measurable aspect of the service that the business can act on.`;

  const userPrompt = `Generate exactly ${count} customer review questions for a **${industryLabel}** business.

Each question must be bilingual (English + Arabic). Primary language emphasis: ${langLabel}.

Return ONLY a JSON array, no other text:
[{"questionEn": "...", "questionAr": "..."}]

Rules:
- Questions must yield actionable insights (not just "how was your experience")
- Arabic must be Modern Standard Arabic appropriate for GCC audiences
- Mix question types: some about specific service aspects, some about staff, some about likelihood to return/recommend
- Each question should help the business identify a specific area to improve or maintain`;

  try {
    const result = await openRouterService.chatCompletion(
      [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userPrompt },
      ],
      {
        model: QUESTION_MODEL,
        maxTokens: 1024,
        temperature: 0.7,
        responseFormat: 'json',
      }
    );

    if (!result.success) {
      log.warn('OpenRouter call failed, using defaults', { error: result.error, industry });
      return getDefaultQuestions(industry, count);
    }

    const parsed = parseQuestionsResponse(result.content);

    if (parsed.length > 0) {
      log.info('AI questions generated', { industry, count: parsed.length, model: result.model });
      return parsed.slice(0, count);
    }

    log.warn('AI returned empty/invalid questions, using defaults', { industry });
    return getDefaultQuestions(industry, count);
  } catch (error) {
    log.error('AI question generation failed, using defaults', { error, industry });
    return getDefaultQuestions(industry, count);
  }
}

/**
 * Get or create a question template for a user + industry combo.
 */
export async function getOrCreateQuestionTemplate(
  userId: string,
  industry: string
): Promise<{
  id: string;
  userId: string;
  industry: string;
  questions: ReviewQuestion[];
  isDefault: boolean;
  createdAt: Date;
  updatedAt: Date;
}> {
  const existing = await convexQuery<ConvexQuestionTemplate>(
    'reviews/queries:getQuestionTemplateByIndustry',
    { userId, industry }
  );

  if (existing) {
    return mapTemplate(existing);
  }

  const questions = await generateReviewQuestions(industry, 'en', 5);

  const created = await convexMutation<ConvexQuestionTemplate>(
    'reviews/mutations:createQuestionTemplate',
    { userId, industry, questions, isDefault: true }
  );

  log.info('Created new question template', { userId, industry });

  return mapTemplate(created!);
}

/**
 * Update questions in an existing template. Verifies ownership before updating.
 */
export async function updateQuestionTemplate(
  userId: string,
  templateId: string,
  questions: ReviewQuestion[]
): Promise<{
  id: string;
  userId: string;
  industry: string;
  questions: ReviewQuestion[];
  isDefault: boolean;
  createdAt: Date;
  updatedAt: Date;
}> {
  const templates = await convexQuery<ConvexQuestionTemplate[]>(
    'reviews/queries:getQuestionTemplates',
    { userId }
  );

  const template = templates?.find(t => t._id === templateId || t.prismaId === templateId);

  if (!template) {
    throw new Error('TEMPLATE_NOT_FOUND');
  }

  if (template.userId !== userId) {
    throw new Error('TEMPLATE_ACCESS_DENIED');
  }

  await convexMutation(
    'reviews/mutations:updateQuestionTemplate',
    { templateId: template._id, questions, isDefault: false }
  );

  log.info('Updated question template', { templateId, userId });

  return mapTemplate({ ...template, questions, isDefault: false, updatedAt: Date.now() });
}

/**
 * List all question templates for a user.
 */
export async function listQuestionTemplates(
  userId: string
): Promise<Array<{
  id: string;
  userId: string;
  industry: string;
  questions: ReviewQuestion[];
  isDefault: boolean;
  createdAt: Date;
  updatedAt: Date;
}>> {
  const templates = await convexQuery<ConvexQuestionTemplate[]>(
    'reviews/queries:getQuestionTemplates',
    { userId }
  );

  return (templates ?? []).map(mapTemplate);
}

/**
 * Delete a question template. Verifies ownership before deleting.
 */
export async function deleteQuestionTemplate(
  userId: string,
  templateId: string
): Promise<void> {
  const templates = await convexQuery<ConvexQuestionTemplate[]>(
    'reviews/queries:getQuestionTemplates',
    { userId }
  );

  const template = templates?.find(t => t._id === templateId || t.prismaId === templateId);

  if (!template) {
    throw new Error('TEMPLATE_NOT_FOUND');
  }

  if (template.userId !== userId) {
    throw new Error('TEMPLATE_ACCESS_DENIED');
  }

  await convexMutation(
    'reviews/mutations:deleteQuestionTemplate',
    { templateId: template._id }
  );

  log.info('Deleted question template', { templateId, userId });
}

// === Internal helpers ===

function getDefaultQuestions(industry: string, count: number): ReviewQuestion[] {
  const key = industry.toLowerCase().replace(/\s+/g, '-');
  const questions = DEFAULT_QUESTIONS[key] ?? DEFAULT_QUESTIONS.general;
  return questions.slice(0, count);
}

function parseQuestionsResponse(text: string): ReviewQuestion[] {
  try {
    const jsonMatch = text.match(/\[[\s\S]*\]/);
    if (!jsonMatch) return [];

    const parsed: unknown = JSON.parse(jsonMatch[0]);
    if (!Array.isArray(parsed)) return [];

    return parsed.filter(
      (item): item is ReviewQuestion =>
        typeof item === 'object' &&
        item !== null &&
        typeof (item as Record<string, unknown>).questionEn === 'string' &&
        typeof (item as Record<string, unknown>).questionAr === 'string' &&
        (item as Record<string, unknown>).questionEn !== '' &&
        (item as Record<string, unknown>).questionAr !== ''
    );
  } catch {
    return [];
  }
}
