// Reply composition via Mastra Agent + free-model fallback chain.
// Mirrors hermes-router.py gen_reply()/build_sys(): persona+context -> system prompt,
// try models in order with per-call timeout + degeneracy guard, first good wins.
import { Agent } from '@mastra/core/agent';
import { loadStyle, getOpenRouterKey, type Ctx } from './hermesConfig';
import type { Persona } from './resolve';
import { badOutput } from './badOutput';

// Free chain (cost rule). owl-alpha FIRST: proven fast+reliable in B0 (Hermes' own
// default model). llama:free as quality fallback. nemotron dropped (timed out in B0).
const MODELS = [
  'openrouter/owl-alpha',
  'meta-llama/llama-3.3-70b-instruct:free',
];
const PER_CALL_MS = 18000;

export function buildSystem(persona: Persona, ctx: Ctx): string {
  const style = loadStyle();
  const rules: string[] = [];
  const rel = (persona.relation ?? '').toLowerCase();

  if (ctx.time_window === 'somn') rules.push('E după 21:00/noaptea - poate doarme; răspuns scurt.');
  if (ctx.time_window === 'cafea' && (rel.includes('coleg') || rel.includes('sef de echipa'))) {
    rules.push('E 08:30-09:00; dacă pare invitație la cafea, spune că mergi/mergem.');
  }
  if (ctx.at_work) rules.push('Adrian e la muncă azi.');
  if (ctx.on_vacation) rules.push('Adrian e plecat/în vacanță.');

  const task =
    `Răspunzi la un mesaj WhatsApp de la ${persona.name ?? ''} (${persona.relation ?? ''}). ` +
    `Tonul tău cu el/ea: ${persona.tone ?? ''}. ` +
    `NU dezvălui niciodată că ești AI. Dacă e ceva important ce cere o decizie pe care nu o poți lua acum, ` +
    `spune scurt că îl anunți pe Adrian și revii repede. Context: ${rules.join(' ') || 'normal'}.`;

  return style + '\n\n--- SARCINA ---\n' + task;
}

function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
  return Promise.race([
    p,
    new Promise<T>((_, rej) => setTimeout(() => rej(new Error(`timeout ${ms}ms`)), ms)),
  ]);
}

export async function compose(
  persona: Persona,
  ctx: Ctx,
  msg: string,
): Promise<{ reply: string; ok: boolean; model: string }> {
  const apiKey = getOpenRouterKey();
  const instructions = buildSystem(persona, ctx);
  let last = '';

  for (const modelId of MODELS) {
    try {
      const agent = new Agent({
        id: 'hermes-compose',
        name: 'hermes-compose',
        instructions,
        model: { providerId: 'openrouter', modelId, url: 'https://openrouter.ai/api/v1', apiKey },
      });
      const res: any = await withTimeout(
        agent.generate(msg, { modelSettings: { maxRetries: 0, temperature: 0.6 } } as any),
        PER_CALL_MS,
      );
      const txt = String(res?.text ?? '').trim();
      last = txt;
      if (!badOutput(txt)) return { reply: txt, ok: true, model: modelId };
    } catch (e: any) {
      last = 'ERR:' + (e?.message ?? e);
    }
  }

  return { reply: last, ok: false, model: '' };
}
