// One-shot diagnostic: prints the state of ANTHROPIC_API_KEY resolution.
// Never prints the key itself — only existence, scope, name, and source.
//
// Run: node scripts/diag-anthropic-key.mjs
import { loadProjectEnv } from '../lib/load-env.js';
loadProjectEnv();

const masterKeySet = Boolean(process.env.MADARX_MASTER_KEY);
const envKeySet = Boolean(process.env.ANTHROPIC_API_KEY);

console.log('MADARX_MASTER_KEY present in env:', masterKeySet);
console.log('ANTHROPIC_API_KEY present in env:', envKeySet);

let secretsModule;
try {
  secretsModule = await import('../lib/secrets.js');
} catch (err) {
  console.error('Failed to import lib/secrets.js:', err.message);
  process.exit(1);
}

const { listSecrets, getSecret } = secretsModule;

try {
  const rows = listSecrets();
  const matching = rows.filter(r => r.name === 'ANTHROPIC_API_KEY');
  console.log('\nlistSecrets() rows where name = "ANTHROPIC_API_KEY":');
  if (matching.length === 0) {
    console.log('  (none)');
  } else {
    for (const r of matching) {
      console.log('  -', { name: r.name, scope: r.scope, project_id: r.project_id, status: r.status, source: r.source, created_at: r.created_at });
    }
  }
  console.log('\nAll active secret names in vault:');
  for (const r of rows) {
    console.log('  -', r.name, '(scope:', r.scope + ')');
  }
} catch (err) {
  console.error('\nlistSecrets() threw:', err.message);
}

try {
  const v = getSecret('ANTHROPIC_API_KEY');
  console.log('\ngetSecret("ANTHROPIC_API_KEY") returned:', v ? `<string length ${v.length}>` : v);
} catch (err) {
  console.error('\ngetSecret threw:', err.message);
}

try {
  const { resolveAnthropicApiKey } = await import('../lib/anthropic-key.js');
  const v = resolveAnthropicApiKey();
  console.log('resolveAnthropicApiKey() returned:', v ? `<string length ${v.length}>` : v);
} catch (err) {
  console.error('resolveAnthropicApiKey threw:', err.message);
}

process.exit(0);
