/**
 * Trust Manager — Track-record and auto-approval logic
 *
 * Computes trust level from checkpoint pass rate history.
 * Enables auto-approval gates for features with proven track records.
 *
 * Trust levels:
 *   low     < 80% pass rate
 *   medium  80–90%
 *   high    90–95%
 *   maximum > 95%
 */

import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';

// Default trust config (matches llm-interaction.json thresholds)
const TRUST_THRESHOLDS = {
  low: 0,
  medium: 0.80,
  high: 0.90,
  maximum: 0.95
};

// Gates that can be auto-approved by trust level
const AUTO_APPROVE_GATES = {
  medium: ['design'],
  high: ['design', 'tasks'],
  maximum: ['design', 'tasks', 'proposal']
};

/**
 * Load state.json
 * @returns {Object} State
 */
function loadState() {
  const statePath = join(process.cwd(), '.morph/state.json');
  if (!existsSync(statePath)) return { features: {} };
  try {
    return JSON.parse(readFileSync(statePath, 'utf8'));
  } catch {
    return { features: {} };
  }
}

/**
 * Save state.json
 * @param {Object} state
 */
function saveState(state) {
  const statePath = join(process.cwd(), '.morph/state.json');
  writeFileSync(statePath, JSON.stringify(state, null, 2), 'utf8');
}

/**
 * Calculate trust level from checkpoint history
 * @param {Array} checkpoints - Array of { passed: boolean, ... }
 * @returns {{ level: string, passRate: number, total: number, passed: number }}
 */
export function calculateTrust(checkpoints = []) {
  if (checkpoints.length === 0) {
    return { level: 'low', passRate: 0, total: 0, passed: 0 };
  }

  const total = checkpoints.length;
  const passed = checkpoints.filter(c => c.passed).length;
  const passRate = passed / total;

  let level = 'low';
  if (passRate >= TRUST_THRESHOLDS.maximum) level = 'maximum';
  else if (passRate >= TRUST_THRESHOLDS.high) level = 'high';
  else if (passRate >= TRUST_THRESHOLDS.medium) level = 'medium';

  return { level, passRate, total, passed };
}

/**
 * Get current trust config for a feature
 * @param {string} featureName
 * @returns {{ level: string, passRate: number, autoApprove: string[], override?: string }}
 */
export function getTrust(featureName) {
  const state = loadState();
  const feature = state.features?.[featureName];

  if (!feature) {
    return { level: 'low', passRate: 0, autoApprove: [], source: 'default' };
  }

  // Check for manual override first
  if (feature.trustConfig?.override) {
    return {
      level: feature.trustConfig.override.level,
      passRate: feature.trustConfig.passRate || 0,
      autoApprove: AUTO_APPROVE_GATES[feature.trustConfig.override.level] || [],
      source: 'manual',
      overrideReason: feature.trustConfig.override.reason,
      overrideAt: feature.trustConfig.override.setAt
    };
  }

  // Calculate from checkpoint history
  const checkpoints = feature.checkpoints || [];
  const { level, passRate, total, passed } = calculateTrust(checkpoints);

  return {
    level,
    passRate,
    total,
    passed,
    autoApprove: AUTO_APPROVE_GATES[level] || [],
    source: 'calculated'
  };
}

/**
 * Manually set trust level with reason
 * @param {string} featureName
 * @param {string} level - 'low' | 'medium' | 'high' | 'maximum'
 * @param {string} reason
 */
export function setTrust(featureName, level, reason) {
  const validLevels = ['low', 'medium', 'high', 'maximum'];
  if (!validLevels.includes(level)) {
    throw new Error(`Invalid trust level: ${level}. Valid: ${validLevels.join(', ')}`);
  }

  const state = loadState();
  if (!state.features[featureName]) {
    throw new Error(`Feature not found: ${featureName}`);
  }

  if (!state.features[featureName].trustConfig) {
    state.features[featureName].trustConfig = {};
  }

  state.features[featureName].trustConfig.override = {
    level,
    reason,
    setAt: new Date().toISOString(),
    setBy: 'manual'
  };

  saveState(state);

  return {
    feature: featureName,
    level,
    autoApprove: AUTO_APPROVE_GATES[level] || [],
    reason
  };
}

/**
 * Clear manual trust override (revert to calculated)
 * @param {string} featureName
 */
export function clearTrustOverride(featureName) {
  const state = loadState();
  if (state.features[featureName]?.trustConfig?.override) {
    delete state.features[featureName].trustConfig.override;
    saveState(state);
  }
}

/**
 * Check if a gate should be auto-approved based on trust level
 * @param {string} featureName
 * @param {string} gate - 'design' | 'tasks' | 'proposal'
 * @returns {{ autoApprove: boolean, level: string, reason: string }}
 */
export function shouldAutoApprove(featureName, gate) {
  const trust = getTrust(featureName);

  if (!trust.autoApprove.includes(gate)) {
    return {
      autoApprove: false,
      level: trust.level,
      reason: `Trust level "${trust.level}" does not auto-approve "${gate}" gate (need: ${getMinLevelForGate(gate)})`
    };
  }

  return {
    autoApprove: true,
    level: trust.level,
    reason: `Auto-approved: ${trust.level} trust (${Math.round(trust.passRate * 100)}% pass rate, ${trust.total} checkpoints)`,
    passRate: trust.passRate,
    checkpointsTotal: trust.total
  };
}

/**
 * Get minimum trust level required for a gate
 * @param {string} gate
 * @returns {string}
 */
function getMinLevelForGate(gate) {
  for (const [level, gates] of Object.entries(AUTO_APPROVE_GATES)) {
    if (gates.includes(gate)) return level;
  }
  return 'maximum';
}

/**
 * Get trust history for all features
 * @returns {Array} Feature trust summaries
 */
export function getTrustHistory() {
  const state = loadState();
  const features = state.features || {};

  return Object.entries(features).map(([name, feature]) => {
    const trust = getTrust(name);
    return {
      feature: name,
      level: trust.level,
      passRate: trust.passRate,
      checkpointsTotal: trust.total || 0,
      checkpointsPassed: trust.passed || 0,
      autoApprove: trust.autoApprove,
      source: trust.source,
      phase: feature.phase,
      status: feature.status
    };
  });
}

/**
 * Auto-calculate and update trust in state
 * @param {string} featureName
 * @returns {Object} Updated trust config
 */
export function autoCalculateTrust(featureName) {
  const state = loadState();
  const feature = state.features?.[featureName];

  if (!feature) {
    throw new Error(`Feature not found: ${featureName}`);
  }

  const checkpoints = feature.checkpoints || [];
  const { level, passRate, total, passed } = calculateTrust(checkpoints);

  if (!state.features[featureName].trustConfig) {
    state.features[featureName].trustConfig = {};
  }

  state.features[featureName].trustConfig = {
    ...state.features[featureName].trustConfig,
    level,
    passRate,
    checkpointsTotal: total,
    checkpointsPassed: passed,
    lastCalculated: new Date().toISOString()
  };

  saveState(state);

  return {
    feature: featureName,
    level,
    passRate,
    total,
    passed,
    autoApprove: AUTO_APPROVE_GATES[level] || []
  };
}

export { TRUST_THRESHOLDS, AUTO_APPROVE_GATES };
