import { Router } from 'express';
import { saveState } from '../services/SaveState.js';
import { behaviorTracker } from '../services/BehaviorTracker.js';
import { narrativePhaseTracker } from '../services/NarrativePhaseTracker.js';
import { endingEvaluator } from '../services/EndingEvaluator.js';

const VALID_PHASES = ['normal_work', 'unease', 'suspicion', 'investigation', 'conflict', 'resolution'];

const router = Router();

router.get('/state', (_req, res) => {
  res.json(saveState.get());
});

router.get('/ending', (_req, res) => {
  res.json(endingEvaluator.evaluate());
});

router.post('/behavior', (req, res) => {
  const { curiosity, obedience, risk, suspicion } = req.body ?? {};
  const isNum = (v) => typeof v === 'number' && v >= 0 && v <= 100;
  const override = {};
  if (isNum(curiosity))  override.curiosity  = curiosity;
  if (isNum(obedience))  override.obedience  = obedience;
  if (isNum(risk))       override.risk       = risk;
  if (isNum(suspicion))  override.suspicion  = suspicion;
  if (Object.keys(override).length === 0) {
    return res.status(400).json({ error: 'No valid fields. Each must be a number 0–100.' });
  }
  behaviorTracker.setSnapshot(override);
  res.json(behaviorTracker.getSnapshot());
});

router.post('/phase', (req, res) => {
  const { phase } = req.body ?? {};
  if (!VALID_PHASES.includes(phase)) {
    return res.status(400).json({ error: `phase must be one of: ${VALID_PHASES.join(', ')}` });
  }
  narrativePhaseTracker.forcePhase(phase);
  res.json({ phase: narrativePhaseTracker.getPhase() });
});

export default router;
