// Deterministic tier resolution — exact port of hermes-router.py resolve().
// Routing is DETERMINISTIC (tier from config); the LLM only writes text later.
import { loadJson, HERMES } from './hermesConfig';

export type Persona = {
  tier: string; // block | ignore | auto | draft
  name?: string;
  relation?: string;
  tone?: string;
};

export function norm(s: string): string {
  return (s || '').replace(/\D/g, '');
}

// Exact key match, else last-9-digit match (handles country-code variance).
function find(dict: Record<string, unknown>, n: string): unknown | null {
  if (n in dict) return dict[n];
  if (n.length >= 9) {
    for (const [k, v] of Object.entries(dict)) {
      if (norm(k).slice(-9) === n.slice(-9)) return v;
    }
  }
  return null;
}

export function resolve(sender: string): Persona {
  const n = norm(sender);

  const block = loadJson<string[]>(HERMES.blocklist, []).map(norm);
  if (block.includes(n) || (n.length >= 9 && block.some((b) => b.slice(-9) === n.slice(-9)))) {
    return { tier: 'block' };
  }

  const p = find(loadJson<Record<string, unknown>>(HERMES.personas, {}), n);
  if (p) return p as Persona;

  const a = find(loadJson<Record<string, unknown>>(HERMES.agenda, {}), n);
  if (a) {
    return {
      tier: 'auto',
      name: a as string,
      relation: 'cunoscut din agenda',
      tone: 'normal, profesional dar natural, prietenos',
    };
  }

  return { tier: 'ignore' };
}
