import type { MxEnvelopeV1 } from '../envelope';

export interface PrincipalContext {
  /** stable key for policy/rate-limit/replay partitioning */
  principalKey: string;
  kind: 'anon' | 'jwt' | 'service';
  iss?: string;
  sub?: string;
  scopes?: string[];
}

/**
 * Derive a stable principal key.
 *
 * For MVP: if JWT claims exist, key = `${iss}:${sub}`.
 * Otherwise fall back to `anon:<fromRealm>` to ensure some partitioning.
 */
export function derivePrincipal(env: MxEnvelopeV1): PrincipalContext {
  const p = env.principal;
  if (p && p.kind === 'jwt' && p.iss && p.sub) {
    return { principalKey: `${p.iss}:${p.sub}`, kind: p.kind, iss: p.iss, sub: p.sub, scopes: p.scopes };
  }
  if (p && p.kind === 'service' && p.sub) {
    return { principalKey: `service:${p.sub}`, kind: p.kind, sub: p.sub, scopes: p.scopes };
  }
  return { principalKey: `anon:${env.from?.root ?? 'unknown'}`, kind: 'anon' };
}
