import { getDb } from '../../db.js';

const T2_FACTS = ['reserve_estimate', 'opex', 'production_schedule'];

function factTypes(projectId) {
  const db = getDb();
  return new Set(db.prepare('SELECT DISTINCT fact_type FROM mines_extracted_facts WHERE project_id = ?').all(projectId).map(r => r.fact_type));
}

function countAssays(projectId) {
  const db = getDb();
  return db.prepare(`
    SELECT COUNT(*) AS n,
           SUM(CASE WHEN au_ppm IS NOT NULL OR ag_ppm IS NOT NULL OR cu_pct IS NOT NULL THEN 1 ELSE 0 END) AS grade_n
    FROM mines_assay_samples WHERE project_id = ?
  `).get(projectId) || { n: 0, grade_n: 0 };
}

export function selectTier(projectId, options = {}) {
  if (!projectId) return { status: 'error', error: 'project_id_required' };
  const db = getDb();
  const project = db.prepare('SELECT id, name, asset_stage, commodity FROM mines_projects WHERE id = ?').get(projectId);
  if (!project) return { status: 'error', error: 'not_found' };

  const types = factTypes(projectId);
  const assay = countAssays(projectId);
  const hasGradeData = (assay.grade_n || 0) > 0;
  const hasResource = types.has('resource_estimate');
  const hasReserve = types.has('reserve_estimate');
  const hasOpex = types.has('opex');
  const hasProduction = types.has('production_schedule');
  const missingT2 = T2_FACTS.filter(t => !types.has(t));
  const t2Ready = missingT2.length === 0;
  const t1Ready = hasResource || hasGradeData;
  const stage = String(project.asset_stage || '').toLowerCase();
  const explorationLike = stage.includes('exploration') || stage.includes('prospect') || stage.includes('early');

  if (options.force_tier === 't1_in_situ') {
    return {
      status: 'ok', project_id: projectId, tier: 't1_in_situ', t1_ready: t1Ready, t2_ready: t2Ready,
      t2_blocked: true, blocking_inputs_missing: missingT2,
      t2_blocking_reason: missingT2.length ? `T2 DCF blocked: missing ${missingT2.join(', ')}.` : 'T1 was explicitly requested.',
      confidence: hasResource ? 'moderate' : 'indicative',
      reason: 'T1 in-situ valuation explicitly requested.',
    };
  }

  if (t2Ready && !explorationLike) {
    return {
      status: 'ok', project_id: projectId, tier: 't2_dcf', t1_ready: t1Ready, t2_ready: true,
      t2_blocked: false, blocking_inputs_missing: [], t2_blocking_reason: null,
      confidence: 'modelled',
      reason: 'Reserve estimate, production schedule, and operating-cost facts are present; DCF is allowed.',
    };
  }

  const forced = options.force_tier === 't2_dcf';
  const explorationBlock = t2Ready && explorationLike ? ['asset_stage_not_dcf_ready'] : [];
  const blocking = [...new Set([...missingT2, ...explorationBlock])];
  return {
    status: 'ok', project_id: projectId, tier: 't1_in_situ', t1_ready: t1Ready, t2_ready: false,
    t2_blocked: true, blocking_inputs_missing: blocking,
    t2_blocking_reason: blocking.length
      ? `T2 DCF blocked: missing or unsuitable inputs (${blocking.join(', ')}).`
      : 'T2 DCF blocked by exploration-stage policy.',
    confidence: hasResource ? 'moderate' : 'indicative',
    reason: forced
      ? 'Forced T2 request was rejected because DCF prerequisites are incomplete or the asset stage is not DCF-ready; using T1 in-situ instead.'
      : 'Exploration/resource-stage projects use T1 in-situ until reserve, production schedule, and cost inputs are present.',
  };
}
