#!/usr/bin/env bash
# ============================================================================
# TC-15 — TMR (Terres Médianes du Rêve)
# Usage: ./tc-15-tmr.sh [--navigate]
# ============================================================================
set -uo pipefail
source "$(dirname "$0")/tc-header.sh"

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-15 — TMR (Terres Médianes du Rêve)                     ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# Setup: créer un acteur HR (haut rêvant)
SETUP=$(jse_get_async "
  const ex = game.actors.getName('TC-15 Test');
  if (ex) await ex.delete();
  const [actor] = await Actor.createDocuments([{
    type: 'personnage', name: 'TC-15 Test',
    system: {
      carac: { force: {value: 12}, reve: {value: 12} },
      reve: { reve: {value: 12}, tmrpos: {coord: 'A1'} },
      sante: { vie: {value: 12, max: 12}, endurance: {value: 20, max: 20} }
    }
  }]);
  return { actorId: actor.id };
")
AID=$(eval_ok "$SETUP" actorId)

# ============================================================================
echo "--- TC-15-002: Génération rencontre TMR ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const a = game.actors.get('$AID');
    if (!a) return {error: 'no actor'};
    // Check TMRRencontres exists
    const { TMRRencontres } = await import('/systems/foundryvtt-reve-de-dragon/module/tmr-rencontres.js');
    const hasRencontres = !!TMRRencontres;
    return { hasRencontres };
  } catch(e) { return {error: e?.message || String(e)}; }
")
HASREN=$(eval_ok "$R" hasRencontres)
ERR=$(eval_ok "$R" error)
[ "$HASREN" = "True" ] && pass "TC-15-002: TMRRencontres module chargé" || fail "TC-15-002: KO ($ERR)"

# ============================================================================
echo "--- TC-15-003: Recherche TMR ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const { TMRUtility } = await import('/systems/foundryvtt-reve-de-dragon/module/tmr-utility.js');
    const tmr = TMRUtility.getTMR('A1');
    return { found: !!tmr, coord: tmr?.coord, type: tmr?.type, label: tmr?.label };
  } catch(e) { return {error: e?.message || String(e)}; }
")
FOUND=$(eval_ok "$R" found)
COORD=$(eval_ok "$R" coord)
ERR=$(eval_ok "$R" error)
[ "$FOUND" = "True" ] && pass "TC-15-003: TMR A1 = $COORD" || fail "TC-15-003: KO ($ERR)"

# ============================================================================
echo "--- TC-15-004: TMR Aléatoire ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const { TMRUtility } = await import('/systems/foundryvtt-reve-de-dragon/module/tmr-utility.js');
    const tmr = TMRUtility.getTMRAleatoire?.() ?? TMRUtility.randomTMR?.();
    return { found: !!tmr, coord: tmr?.coord, type: tmr?.type };
  } catch(e) { return {error: e?.message || String(e)}; }
")
FOUND=$(eval_ok "$R" found)
COORD=$(eval_ok "$R" coord)
ERR=$(eval_ok "$R" error)
[ "$FOUND" = "True" ] && pass "TC-15-004: TMR aléatoire = $COORD" || fail "TC-15-004: KO ($ERR)"

# ============================================================================
echo "--- TC-15-006: Coordonnées TMR acteur ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const a = game.actors.get('$AID');
    if (!a) return {error: 'no actor'};
    await a.update({'system.reve.tmrpos.coord': 'M5'});
    await new Promise(r => setTimeout(r, 500));
    const coord = a.system.reve?.tmrpos?.coord;
    return { coord, ok: coord === 'M5' };
  } catch(e) { return {error: e?.message || String(e)}; }
")
COORD=$(eval_ok "$R" coord)
OK=$(eval_ok "$R" ok)
ERR=$(eval_ok "$R" error)
[ "$OK" = "True" ] && pass "TC-15-006: coord TMR acteur = $COORD" || fail "TC-15-006: KO ($ERR)"

# ============================================================================
echo "--- TC-15-007: Réinsertion aléatoire ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const a = game.actors.get('$AID');
    if (!a) return {error: 'no actor'};
    if (typeof a.reinsertionAleatoire !== 'function') return {error: 'no reinsertionAleatoire'};
    await a.reinsertionAleatoire();
    await new Promise(r => setTimeout(r, 500));
    const coord = a.system.reve?.tmrpos?.coord;
    return { newCoord: coord, changed: coord !== 'M5' };
  } catch(e) { return {error: e?.message || String(e)}; }
")
NEWC=$(eval_ok "$R" newCoord)
CHANGED=$(eval_ok "$R" changed)
ERR=$(eval_ok "$R" error)
[ "$CHANGED" = "True" ] && pass "TC-15-007: réinsertion = $NEWC" || fail "TC-15-007: KO ($ERR)"

# ============================================================================
echo ""
echo "--- Cleanup ---"
CLEANUP=$(jse_get_async "
  const a = game.actors.getName('TC-15 Test');
  if (a) { await a.delete(); return 'deleted'; }
  return 'none';
" | tr -d '"\n')
[ "$CLEANUP" = "deleted" ] && pass "Cleanup: actor deleted" || fail "Cleanup: $CLEANUP"

echo ""
echo "--- Console errors ---"
ERRS=$(tc_console_errors)
[ "$ERRS" -le 5 ] 2>/dev/null && pass "Console errors ≤5 ($ERRS)" || fail "Console errors: $ERRS"

tc_summary