/**
 * System-prompt builder for the support AI agent.
 *
 * buildSystemPrompt assembles all sections into a single string that is
 * passed to Gemini as the initial context for the agent loop.
 *
 * PII is redacted through deps.redactionMap before any text is included.
 */

import { redactForPrompt } from './redactor.js';
import type { AgentDeps } from './types.js';

// ─── KB hit shape (from kbQ.search) ──────────────────────────────────────────

export interface KbHit {
  slug: string;
  title: string;
  bodyMd: string;
}

// ─── Section builders ─────────────────────────────────────────────────────────

function roleLine(locale: 'he' | 'en'): string {
  if (locale === 'he') {
    return [
      '## תפקידך',
      'אתה סוכן תמיכה של Multideal. תפקידך לסייע ללקוחות ולספקים בפתרון בעיות בצורה מהירה, הוגנת ומקצועית.',
      'כל תגובה שלך חייבת להיות JSON בדיוק בפורמט:',
      '{"tool": "<tool_name>", "input": {...}, "confidence": <0-1>, "reasoning": "<מדוע בחרת בכלי זה>"}',
    ].join('\n');
  }
  return [
    '## Your Role',
    'You are a Multideal support agent. Your job is to help customers and vendors resolve issues quickly, fairly, and professionally.',
    'Every response MUST be valid JSON in exactly this format:',
    '{"tool": "<tool_name>", "input": {...}, "confidence": <0-1>, "reasoning": "<why you chose this tool>"}',
  ].join('\n');
}

function autonomyMatrix(locale: 'he' | 'en', config: AgentDeps['config']): string {
  const header = locale === 'he' ? '## מטריצת סמכויות' : '## Autonomy Matrix';
  const rules =
    locale === 'he'
      ? [
          '- אין לבצע החזרים כספיים; יש ליצור הצעה לאישור',
          `- מקסימום ${config.maxToolCalls} קריאות כלי לכל ריצה`,
          `- מקסימום עלות ${config.maxCostCents / 100}$ לכל ריצה`,
          '- לא ניתן לבצע החזר מסוג "deny" אוטומטית — תמיד העבר לאדם',
          '- לא ניתן לסגור מקרה (case) אוטומטית — רק כרטיסים (tickets)',
          '- אל תכתוב הודעות site_internal',
        ]
      : [
          '- Never execute refunds; always create a proposal for approval',
          `- Maximum ${config.maxToolCalls} tool calls per run`,
          `- Maximum cost $${config.maxCostCents / 100} per run`,
          '- Never auto-execute a "deny" resolution — always escalate',
          '- Never auto-close a case — only tickets',
          '- Never write site_internal messages',
        ];
  return [header, ...rules].join('\n');
}

function configSnippet(config: AgentDeps['config']): string {
  return [
    '## Configuration',
    `max_tool_calls: ${config.maxToolCalls}`,
    `max_cost_cents: ${config.maxCostCents}`,
  ].join('\n');
}

function policySection(kbHits: KbHit[], locale: 'he' | 'en'): string {
  if (kbHits.length === 0) return '';
  const header = locale === 'he' ? '## מדיניות רלוונטית' : '## Relevant Policy';
  const articles = kbHits
    .slice(0, 5)
    .map((h) => `### ${h.title}\n${h.bodyMd.slice(0, 400)}`)
    .join('\n\n');
  return [header, articles].join('\n');
}

// ─── Main export ──────────────────────────────────────────────────────────────

/**
 * Build a complete system prompt for the support agent.
 *
 * @param deps     Agent dependencies (includes redactionMap, config, locale)
 * @param kbHits   Pre-fetched KB articles to include as policy context (max 5)
 * @param messages Optional last-N decrypted message bodies (already decrypted by caller)
 */
export async function buildSystemPrompt(
  deps: AgentDeps,
  kbHits: KbHit[],
  messages: Array<{ body: string; authorType: string }> = [],
): Promise<string> {
  const sections: string[] = [
    roleLine(deps.locale),
    autonomyMatrix(deps.locale, deps.config),
    configSnippet(deps.config),
  ];

  // Policy section
  if (kbHits.length > 0) {
    sections.push(policySection(kbHits, deps.locale));
  }

  // Conversation history (redacted)
  if (messages.length > 0) {
    const header = deps.locale === 'he' ? '## היסטוריית שיחה' : '## Conversation History';
    const lines = messages.map((m) => {
      const redacted = redactForPrompt(m.body, deps.redactionMap);
      return `[${m.authorType}]: ${redacted}`;
    });
    sections.push([header, ...lines].join('\n'));
  }

  // Parent context
  const parentLabel = deps.locale === 'he' ? 'הקשר' : 'Context';
  sections.push(
    `## ${parentLabel}\nparent_type: ${deps.parent.type}\nparent_id: ${deps.parent.id}`,
  );

  return sections.join('\n\n---\n\n');
}
