/**
 * Phase 7 (2026-04-29) — Flow judiciaire step-by-step.
 *
 * 2 étapes confirmées : Garde à vue (24/48/72h selon crime) → Jugement.
 *
 * À chaque étape, le joueur choisit via `JudicialFlowModal` :
 *   - Garder le silence (GAV) → flow continue à la transition auto
 *   - Avocat commis d'office (cost) → roll pondéré sur 4 (GAV) ou 5 (jugement) issues
 *   - Avocat personnel (Specialist lawyer attaché, gratuit) → idem mais bonus poids+effets
 *   - Bakchich direct (sans tirage) → débit + libération si fonds OK
 *   - [Jugement uniquement] Utiliser un item (Alibi/Jurisprudence/Vice de procédure)
 *
 * Tous les barèmes (poids, modulateurs, tarifs) sont dans constants/judicial-flow.ts
 * et surchargeables via game_settings (sandbox admin sans redéploiement).
 */
import { AppDataSource } from '../config/database';
import { In } from 'typeorm';
import { CriminalRecord, JudicialStep, LawyerChoice, JudicialOutcome } from '../models/CriminalRecord';
import { Player } from '../models/Player';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerGauges } from '../models/PlayerGauges';
import { PoliceFile } from '../models/PoliceFile';
import { Specialist } from '../models/Specialist';
import { SpecialistAttachment } from '../models/SpecialistAttachment';
import { Notification } from '../models/Notification';
import { emitToPlayer } from '../gateways/map.gateway';
import { GameSettingsService } from './game-settings.service';
import {
  PHASE7_DEFAULTS,
  skillToStars,
  lawyerMultiplier,
  computeBakchichWeight,
  rollWeighted,
  computeFineAmount,
  computeLawyerOfficeJugementCost,
  computeBakchichJugeAmount,
  type JudicialIssueGav,
  type JudicialIssueJugement,
} from '../constants/judicial-flow';
import { TransactionService } from './transaction.service';

const recordRepo = () => AppDataSource.getRepository(CriminalRecord);
const playerRepo = () => AppDataSource.getRepository(Player);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const fileRepo = () => AppDataSource.getRepository(PoliceFile);
const attRepo = () => AppDataSource.getRepository(SpecialistAttachment);
const notifRepo = () => AppDataSource.getRepository(Notification);

export type StepChoice =
  | 'silence'
  | 'office'
  | 'personal'
  | 'bakchich_direct';

export interface StepContext {
  chaleur: number;
  conscience: number;
  influence: number;
  respect: number;
  pouvoir: number;
  degree: number;
  incarceration_count: number;
  is_violent: boolean;
  lawyer_skill: number; // 1-10 (default 3 = office 2★ UI)
  light_balance: number;
  shadow_balance: number;
}

export interface JudicialStepResult {
  step: JudicialStep;
  outcome?: JudicialOutcome;
  issue_rolled?: JudicialIssueGav | JudicialIssueJugement;
  cost_paid?: number;
  fine_amount?: number;
  fine_loan_id?: string;
  bakchich_proposed?: { kind: 'gav' | 'juge'; amount: number };
  imprisoned_until?: string;
  flavor: string;
}

export class JudicialFlowService {
  // ──────────────────────────────────────────────────────────
  //  CONTEXT BUILDER (gather all stats for weight computation)
  // ──────────────────────────────────────────────────────────
  static async buildContext(playerId: string, recordId: string): Promise<StepContext> {
    const [gauges, file, balance, record] = await Promise.all([
      gaugesRepo().findOneBy({ player_id: playerId }),
      fileRepo().findOneBy({ player_id: playerId }),
      balancesRepo().findOneBy({ player_id: playerId }),
      recordRepo().findOneBy({ id: recordId }),
    ]);

    // Find best attached lawyer (highest skill_level)
    let lawyer_skill = 3; // commis d'office baseline = 2★ UI (skill 3)
    const att = await attRepo()
      .createQueryBuilder('sa')
      .innerJoinAndSelect(Specialist, 's', 's.id = sa.specialist_id')
      .where('sa.owner_type = :ot', { ot: 'player' })
      .andWhere('sa.owner_id = :oid', { oid: playerId })
      .andWhere('sa.is_active = true')
      .andWhere('s.role = :role', { role: 'lawyer' })
      .orderBy('s.skill_level', 'DESC')
      .limit(1)
      .getRawOne();
    if (att) lawyer_skill = Number(att.s_skill_level || lawyer_skill);

    return {
      chaleur: Number(gauges?.chaleur ?? 0),
      conscience: Number(gauges?.conscience ?? 50),
      influence: Number(gauges?.influence ?? 0),
      respect: Number(gauges?.respect ?? 0),
      pouvoir: Number(gauges?.pouvoir ?? 0),
      degree: Number(file?.degree ?? 0),
      incarceration_count: Number(file?.incarceration_count ?? 0),
      is_violent: !!record?.is_violent,
      lawyer_skill,
      light_balance: Number(balance?.infinite_light ?? 0),
      shadow_balance: Number(balance?.infinite_shadow ?? 0),
    };
  }

  // ──────────────────────────────────────────────────────────
  //  WEIGHTS COMPUTATION
  // ──────────────────────────────────────────────────────────
  private static computeGavWeights(ctx: StepContext): Record<JudicialIssueGav, number> {
    const stars = skillToStars(ctx.lawyer_skill);
    const m = PHASE7_DEFAULTS;

    const wLibere = m.weights_gav.libere
      + (50 - ctx.chaleur) * m.modifiers_gav_libere.chaleur_factor
      + (ctx.conscience - 50) * m.modifiers_gav_libere.conscience_factor
      + (ctx.influence - 50) * m.modifiers_gav_libere.influence_factor
      + stars * m.modifiers_gav_libere.skill_factor
      - ctx.incarceration_count * m.modifiers_gav_libere.incarceration_penalty
      - ctx.degree * m.modifiers_gav_libere.degree_penalty
      - (ctx.is_violent ? m.modifiers_gav_libere.violent_penalty : 0);

    const wAmende = m.weights_gav.amende
      + (50 - ctx.chaleur) * m.modifiers_gav_amende.chaleur_factor
      + stars * m.modifiers_gav_amende.skill_factor
      + (ctx.respect - 50) * m.modifiers_gav_amende.respect_factor;

    // Bakchich : formule user + check fonds
    const bakchichAmount = m.bakchich_gav_amount;
    const hasFunds = ctx.shadow_balance >= bakchichAmount || ctx.light_balance >= bakchichAmount;
    const wBakchich = hasFunds
      ? computeBakchichWeight(ctx.chaleur, ctx.respect, stars)
      : 0;

    const wStep = m.weights_gav.step
      + ctx.chaleur * m.modifiers_gav_step.chaleur_factor
      + ctx.degree * m.modifiers_gav_step.degree_factor
      + ctx.incarceration_count * m.modifiers_gav_step.incarceration_factor
      + (ctx.is_violent ? m.modifiers_gav_step.violent_bonus : 0)
      - stars * m.modifiers_gav_step.skill_penalty;

    const clamp = (v: number) =>
      Math.max(m.weight_floor, Math.min(m.weight_cap, Math.round(v)));

    return {
      libere: clamp(wLibere),
      amende: ctx.light_balance < computeFineAmount(ctx.chaleur, ctx.degree, ctx.is_violent)
        ? 0 // pas les fonds pour l'amende min → poids 0 + redistribution
        : clamp(wAmende),
      bakchich: wBakchich, // déjà clamp dans computeBakchichWeight
      step: clamp(wStep),
    };
  }

  private static computeJugementWeights(ctx: StepContext): Record<JudicialIssueJugement, number> {
    const stars = skillToStars(ctx.lawyer_skill);
    const m = PHASE7_DEFAULTS;

    const wLibcond = m.weights_jugement.liberation_conditionnelle
      + (50 - ctx.chaleur) * m.modifiers_jug_libcond.chaleur_factor
      + (ctx.conscience - 50) * m.modifiers_jug_libcond.conscience_factor
      + stars * m.modifiers_jug_libcond.skill_factor
      - ctx.incarceration_count * m.modifiers_jug_libcond.incarceration_penalty
      - ctx.degree * m.modifiers_jug_libcond.degree_penalty
      - (ctx.is_violent ? m.modifiers_jug_libcond.violent_penalty : 0);

    const wLibcondAmende = m.weights_jugement.lib_cond_amende
      + (50 - ctx.chaleur) * m.modifiers_jug_libcond_amende.chaleur_factor
      + stars * m.modifiers_jug_libcond_amende.skill_factor
      + (ctx.influence - 50) * m.modifiers_jug_libcond_amende.influence_factor;

    const bakchichJugeAmount = computeBakchichJugeAmount(ctx.chaleur, ctx.degree, ctx.is_violent);
    const hasJugeFunds = ctx.shadow_balance >= bakchichJugeAmount;
    const wBakchichJuge = hasJugeFunds
      ? computeBakchichWeight(ctx.chaleur, ctx.respect, stars)
      : 0;

    const wReduced50 = m.weights_jugement.reduced_50
      + stars * m.modifiers_jug_reduced_50.skill_factor
      + ctx.degree * m.modifiers_jug_reduced_50.degree_factor;

    const wReduced25 = m.weights_jugement.reduced_25
      + ctx.chaleur * m.modifiers_jug_reduced_25.chaleur_factor
      + (ctx.is_violent ? m.modifiers_jug_reduced_25.violent_bonus : 0)
      + ctx.degree * m.modifiers_jug_reduced_25.degree_factor
      - stars * m.modifiers_jug_reduced_25.skill_penalty;

    const clamp = (v: number) =>
      Math.max(m.weight_floor, Math.min(m.weight_cap, Math.round(v)));

    const fineAmount = computeFineAmount(ctx.chaleur, ctx.degree, ctx.is_violent);
    return {
      liberation_conditionnelle: clamp(wLibcond),
      lib_cond_amende: ctx.light_balance < fineAmount ? 0 : clamp(wLibcondAmende),
      bakchich_juge: wBakchichJuge,
      reduced_50: clamp(wReduced50),
      reduced_25: clamp(wReduced25),
    };
  }

  // ──────────────────────────────────────────────────────────
  //  LIFECYCLE : enterGardeAVue → chooseLawyerAtStep → applyIssue → next
  // ──────────────────────────────────────────────────────────

  /**
   * Démarre le flow judiciaire après une arrestation.
   * Si le joueur a déjà un flow actif (autre record en garde_a_vue/jugement),
   * cette nouvelle charge est mise en attente (judicial_step='pending').
   */
  static async enterGardeAVue(playerId: string, recordId: string): Promise<void> {
    const record = await recordRepo().findOneBy({ id: recordId });
    if (!record) throw new Error('Record introuvable');
    if (record.player_id !== playerId) throw new Error('Record n\'appartient pas au joueur');

    // Check si flow déjà actif
    const active = await JudicialFlowService.getActiveFlowRecord(playerId);
    if (active && active.id !== recordId) {
      // Déjà un flow actif → cette charge reste pending (sera reprise au prochain crime/incarcération)
      return;
    }

    // Durée GAV selon crime_type (game_settings overridable)
    const durations = await GameSettingsService.get(
      'judicial.gav.duration_h',
      PHASE7_DEFAULTS.gav_duration_hours,
    );
    const hours = durations[record.crime_type] ?? 24;
    const nextStepAt = new Date(Date.now() + hours * 3600 * 1000);

    await recordRepo().update(
      { id: recordId },
      { judicial_step: 'garde_a_vue' as JudicialStep, next_step_at: nextStepAt },
    );

    // Notif + WS event pour ouvrir le modal frontend
    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: 'Garde à vue',
        message: `Vous êtes en garde à vue (${hours}h max). Appelez votre avocat rapidement.`,
      }));
    } catch { /* silent */ }

    emitToPlayer(playerId, 'judicial:step-changed', {
      record_id: recordId,
      step: 'garde_a_vue',
      next_step_at: nextStepAt.toISOString(),
      crime_type: record.crime_type,
      gav_duration_hours: hours,
    });
  }

  /**
   * Joueur clique un bouton (silence / office / personal / bakchich_direct).
   * Pour 'silence' : ne fait rien, le flow continue automatiquement à `next_step_at`.
   * Pour 'office'/'personal' : débit avocat (si applicable), tirage pondéré, applique l'issue.
   * Pour 'bakchich_direct' : débit 2000∞ (GAV) ou bakchich juge (jugement), libération directe.
   */
  static async chooseLawyerAtStep(
    playerId: string,
    recordId: string,
    choice: StepChoice,
  ): Promise<JudicialStepResult> {
    const record = await recordRepo().findOneBy({ id: recordId });
    if (!record) throw new Error('Record introuvable');
    if (record.player_id !== playerId) throw new Error('Record n\'appartient pas au joueur');
    if (record.judicial_step !== 'garde_a_vue' && record.judicial_step !== 'jugement') {
      throw new Error(`Step invalide: ${record.judicial_step} (flow non actif)`);
    }

    const ctx = await JudicialFlowService.buildContext(playerId, recordId);
    const isJugement = record.judicial_step === 'jugement';

    // ─── SILENCE : passive — flow continue au timer
    if (choice === 'silence') {
      return {
        step: record.judicial_step,
        flavor: isJugement
          ? 'Vous restez muet face au juge. La sentence tombera sans plaidoirie.'
          : 'Vous gardez le silence. Les heures de garde à vue défilent…',
      };
    }

    // ─── BAKCHICH DIRECT (sans tirage)
    if (choice === 'bakchich_direct') {
      const amount = isJugement
        ? computeBakchichJugeAmount(ctx.chaleur, ctx.degree, ctx.is_violent)
        : PHASE7_DEFAULTS.bakchich_gav_amount;
      const stars = skillToStars(ctx.lawyer_skill);
      const mult = lawyerMultiplier(ctx.lawyer_skill);
      // Multiplicateur réduit le bakchich (négatif) : amount × (2 - mult)
      const finalAmount = Math.round(amount * (2 - mult));
      // Bakchich toujours en shadow (consigne user simplifiée — ∞ ombre)
      const currency = 'infinite_shadow' as const;

      const balance = await balancesRepo().findOneBy({ player_id: playerId });
      const have = Number(balance?.infinite_shadow ?? 0);
      if (have < finalAmount) {
        throw new Error(`Fonds insuffisants : ${finalAmount} ∞ shadow requis (avez ${have}).`);
      }

      await balancesRepo().decrement({ player_id: playerId }, currency, finalAmount);
      await TransactionService.log({
        player_id: playerId, category: 'crime', type: 'out',
        amount: finalAmount, currency,
        description: isJugement ? 'Bakchich juge (direct)' : 'Bakchich commissaire (direct)',
      });
      await recordRepo().update(
        { id: recordId },
        {
          judicial_step: 'released' as JudicialStep,
          lawyer_choice: 'bakchich_direct' as LawyerChoice,
          paid_amount: record.paid_amount + finalAmount,
          outcome: 'released_via_bakchich' as JudicialOutcome,
          next_step_at: null,
        },
      );

      const flavor = isJugement
        ? `Le juge empoche l'enveloppe. « Affaire classée. » Tu rentres chez toi (${finalAmount.toLocaleString('fr-FR')} ∞ shadow envolés).`
        : `Le commissaire glisse l'enveloppe dans son tiroir. « Allez, dégage. » Tu sors par la porte de derrière (${finalAmount.toLocaleString('fr-FR')} ∞ shadow ${stars > 1 ? `— mult avocat -${Math.round((1 - (2 - mult)) * 100)}%` : ''}).`;

      try {
        await notifRepo().save(notifRepo().create({
          player_id: playerId,
          type: 'system',
          title: 'Bakchich accepté',
          message: flavor,
        }));
      } catch { /* silent */ }

      emitToPlayer(playerId, 'judicial:step-changed', {
        record_id: recordId,
        step: 'released',
        outcome: 'released_via_bakchich',
      });

      return {
        step: 'released',
        outcome: 'released_via_bakchich',
        cost_paid: finalAmount,
        flavor,
      };
    }

    // ─── OFFICE ou PERSONAL : débit avocat (si applicable) + tirage pondéré
    let lawyerCost = 0;
    if (choice === 'office') {
      lawyerCost = isJugement
        ? computeLawyerOfficeJugementCost(ctx.chaleur)
        : PHASE7_DEFAULTS.lawyer_office_gav_cost;

      const balance = await balancesRepo().findOneBy({ player_id: playerId });
      if (Number(balance?.infinite_light ?? 0) < lawyerCost) {
        throw new Error(`Fonds insuffisants : ${lawyerCost} ∞ light requis pour l'avocat commis d'office.`);
      }
      await balancesRepo().decrement({ player_id: playerId }, 'infinite_light', lawyerCost);
      await TransactionService.log({
        player_id: playerId, category: 'crime', type: 'out',
        amount: lawyerCost, currency: 'infinite_light',
        description: `Avocat commis d'office (${isJugement ? 'jugement' : 'GAV'})`,
      });
    }
    // 'personal' : gratuit (déjà payé par paySalaries cron)

    // Bonus poids quand 'personal' — l'avocat perso améliore les chances
    const ctxBoosted = { ...ctx };
    if (choice === 'office') {
      // Office baseline : skill 3 (2★ UI)
      ctxBoosted.lawyer_skill = 3;
    }
    // Si 'personal', ctx.lawyer_skill est déjà celui du Specialist attaché

    let issue: JudicialIssueGav | JudicialIssueJugement;
    let weights: Record<string, number>;
    if (isJugement) {
      weights = JudicialFlowService.computeJugementWeights(ctxBoosted);
      issue = rollWeighted(weights as Record<JudicialIssueJugement, number>);
    } else {
      weights = JudicialFlowService.computeGavWeights(ctxBoosted);
      issue = rollWeighted(weights as Record<JudicialIssueGav, number>);
    }

    const result = await JudicialFlowService.applyIssue(
      playerId, recordId, issue, choice, ctxBoosted, lawyerCost,
    );
    return result;
  }

  /**
   * Applique l'issue tirée (debit/credit, set imprisoned, créer amende, etc.).
   */
  private static async applyIssue(
    playerId: string,
    recordId: string,
    issue: JudicialIssueGav | JudicialIssueJugement,
    choice: StepChoice,
    ctx: StepContext,
    lawyerCost: number,
  ): Promise<JudicialStepResult> {
    const record = await recordRepo().findOneBy({ id: recordId });
    if (!record) throw new Error('Record introuvable');
    const mult = lawyerMultiplier(ctx.lawyer_skill);
    const stars = skillToStars(ctx.lawyer_skill);
    const newPaidAmount = record.paid_amount + lawyerCost;

    const finalChoice: LawyerChoice =
      choice === 'office' ? 'office' :
      choice === 'personal' ? 'personal' :
      choice === 'silence' ? 'none' :
      'bakchich_direct';

    // ─────── GAV ───────
    if (issue === 'libere') {
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'released' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        outcome: 'released_via_lawyer' as JudicialOutcome,
        next_step_at: null,
      });
      const flavor = `L'avocat plaide. Le commissaire grogne. Tu sors libre — pour cette fois.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'released', outcome: 'released_via_lawyer', issue });
      return { step: 'released', outcome: 'released_via_lawyer', issue_rolled: issue, cost_paid: lawyerCost, flavor };
    }

    if (issue === 'amende') {
      // Créer amende via CourtFineService
      const fineAmount = Math.round(computeFineAmount(ctx.chaleur, ctx.degree, ctx.is_violent) * (2 - mult));
      const { CourtFineService } = await import('./court-fine.service');
      const loan = await CourtFineService.createFine(playerId, recordId, fineAmount);
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'fine_active' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        outcome: 'fine_only' as JudicialOutcome,
        next_step_at: null,
      });
      const flavor = `Sortie immédiate, mais avec une amende sur 30 jours. ${fineAmount.toLocaleString('fr-FR')} ∞ light à régler${stars > 2 ? ` (réduit de ${Math.round((1 - (2 - mult)) * 100)}% par votre avocat)` : ''}.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'fine_active', outcome: 'fine_only', issue, fine_amount: fineAmount });
      return { step: 'fine_active', outcome: 'fine_only', issue_rolled: issue, cost_paid: lawyerCost, fine_amount: fineAmount, fine_loan_id: loan.id, flavor };
    }

    if (issue === 'bakchich') {
      // Issue bakchich tirée → propose au joueur (lightbox accept/refuse)
      const amount = PHASE7_DEFAULTS.bakchich_gav_amount;
      // Note : flow attend respondToBakchich (côté joueur)
      // On ne touche pas au step, on flag juste le bakchich proposé
      await recordRepo().update({ id: recordId }, {
        lawyer_choice: 'bakchich_accepted' as LawyerChoice, // sera refused si refuse
        paid_amount: newPaidAmount,
      });
      const flavor = `Le commissaire vous regarde. « 2 000 ∞ et on oublie tout. Cash. » Vous acceptez ?`;
      emitToPlayer(playerId, 'judicial:bakchich-proposed', {
        record_id: recordId,
        step: 'garde_a_vue',
        kind: 'gav',
        amount,
      });
      return { step: 'garde_a_vue', issue_rolled: issue, cost_paid: lawyerCost, bakchich_proposed: { kind: 'gav', amount }, flavor };
    }

    if (issue === 'step') {
      // Transition vers jugement
      const transitionAt = new Date(Date.now() + 30 * 60 * 1000); // 30min pour réagir
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'jugement' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        next_step_at: transitionAt,
      });

      // Phase 8.5d (2026-04-29) — Téléporte le joueur au tribunal le plus
      // proche au passage en step 'jugement' (spec user : "lors du jugement
      // le point est déplacé au tribunal le plus proche").
      try {
        const { NearestPoiService } = await import('./nearest-poi.service');
        const { Player } = await import('../models/Player');
        const playerRepoLocal = AppDataSource.getRepository(Player);
        const player = await playerRepoLocal.findOneBy({ id: playerId });
        if (player) {
          const fromLat = Number(player.current_lat) || Number(player.start_lat) || 48.8566;
          const fromLon = Number(player.current_lon) || Number(player.start_lon) || 2.3522;
          const courthouse = await NearestPoiService.findNearestCourthouse(fromLat, fromLon);
          if (courthouse) {
            await playerRepoLocal.update({ id: playerId }, {
              current_lat: courthouse.lat,
              current_lon: courthouse.lon,
              in_transit: false,
              active_vehicle_id: null,
            });
          }
        }
      } catch (err) {
        console.error('[JudicialFlow] teleport tribunal failed:', (err as Error).message);
      }

      const flavor = `Le procureur monte le dossier. Vous êtes présenté au tribunal.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'jugement', issue, next_step_at: transitionAt.toISOString() });
      return { step: 'jugement', issue_rolled: issue, cost_paid: lawyerCost, flavor };
    }

    // ─────── JUGEMENT ───────
    if (issue === 'liberation_conditionnelle') {
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'released' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        outcome: 'liberation_conditionnelle' as JudicialOutcome,
        next_step_at: null,
      });
      const flavor = `Libération conditionnelle accordée. Pas de prison, pas d'amende. Tu rentres chez toi.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'released', outcome: 'liberation_conditionnelle', issue });
      return { step: 'released', outcome: 'liberation_conditionnelle', issue_rolled: issue, cost_paid: lawyerCost, flavor };
    }

    if (issue === 'lib_cond_amende') {
      const fineAmount = Math.round(computeFineAmount(ctx.chaleur, ctx.degree, ctx.is_violent) * (2 - mult));
      const { CourtFineService } = await import('./court-fine.service');
      const loan = await CourtFineService.createFine(playerId, recordId, fineAmount);
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'fine_active' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        outcome: 'fine_only' as JudicialOutcome,
        next_step_at: null,
      });
      const flavor = `Liberation conditionnelle + amende ${fineAmount.toLocaleString('fr-FR')} ∞ sur 30j. Si tu ne paies pas un jour : 1 jour de prison.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'fine_active', outcome: 'fine_only', issue, fine_amount: fineAmount });
      return { step: 'fine_active', outcome: 'fine_only', issue_rolled: issue, cost_paid: lawyerCost, fine_amount: fineAmount, fine_loan_id: loan.id, flavor };
    }

    if (issue === 'bakchich_juge') {
      const amount = computeBakchichJugeAmount(ctx.chaleur, ctx.degree, ctx.is_violent);
      const flavor = `Le juge demande à vous parler en privé. « ${amount.toLocaleString('fr-FR')} ∞ shadow et l'affaire est classée. » Vous acceptez ?`;
      emitToPlayer(playerId, 'judicial:bakchich-proposed', {
        record_id: recordId,
        step: 'jugement',
        kind: 'juge',
        amount,
      });
      return { step: 'jugement', issue_rolled: issue, cost_paid: lawyerCost, bakchich_proposed: { kind: 'juge', amount }, flavor };
    }

    if (issue === 'reduced_50' || issue === 'reduced_25') {
      // Convict avec peine réduite
      const baseDays = record.sentence_days || 0;
      let reductionFactor = issue === 'reduced_50' ? 0.5 : 0.75;
      // Avocat perso boost positif : 50% → 60..100%, 25% → 35..75%
      if (ctx.lawyer_skill > 3) {
        const bonus = (mult - 1.2); // base office mult = 1.2 → bonus = 0..0.3 (5★)
        reductionFactor = issue === 'reduced_50'
          ? Math.max(0, 0.5 - bonus)        // 5★ → 0.5 - 0.3 = 0.2 (donc 80% réduit, presque annulé)
          : Math.max(0.25, 0.75 - bonus);   // 5★ → 0.75 - 0.3 = 0.45 (55% réduit)
      }
      const finalDays = Math.max(0, Math.round(baseDays * reductionFactor));
      await recordRepo().update({ id: recordId }, {
        judicial_step: 'imprisoned' as JudicialStep,
        lawyer_choice: finalChoice,
        paid_amount: newPaidAmount,
        outcome: issue as JudicialOutcome,
        sentence_days: finalDays,
        next_step_at: null,
      });

      // Trigger l'incarcération via PrisonAssignmentService
      try {
        const { PrisonAssignmentService } = await import('./prison-assignment.service');
        if (finalDays > 0) {
          await PrisonAssignmentService.assignPrison(playerId, finalDays);
        }
      } catch (err) {
        console.error('[JudicialFlow] assignPrison error:', (err as Error).message);
      }

      const reductionPct = issue === 'reduced_50' ? 50 : 25;
      const flavor = finalDays === 0
        ? `Le juge prononce la peine, mais votre avocat 5★ obtient l'annulation totale. Tu sors libre.`
        : `Peine réduite de ${reductionPct}%. ${finalDays} jour(s) à tirer.`;
      emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'imprisoned', outcome: issue, issue, sentence_days: finalDays });
      return { step: 'imprisoned', outcome: issue as JudicialOutcome, issue_rolled: issue, cost_paid: lawyerCost, flavor };
    }

    // Cas dégénéré (ne devrait pas arriver)
    return { step: record.judicial_step, flavor: 'Erreur: issue inconnue.' };
  }

  /**
   * Bakchich proposé → user accepte ou refuse.
   *   - accept + fonds OK : débit + libéré
   *   - accept + fonds KO : refuse forcé → flow continue (jugement ou prison)
   *   - refuse : flow continue
   */
  static async respondToBakchich(
    playerId: string,
    recordId: string,
    accepts: boolean,
  ): Promise<JudicialStepResult> {
    const record = await recordRepo().findOneBy({ id: recordId });
    if (!record) throw new Error('Record introuvable');
    if (record.player_id !== playerId) throw new Error('Record n\'appartient pas au joueur');

    const ctx = await JudicialFlowService.buildContext(playerId, recordId);
    const isJugement = record.judicial_step === 'jugement';
    const stars = skillToStars(ctx.lawyer_skill);
    const mult = lawyerMultiplier(ctx.lawyer_skill);

    if (!accepts) {
      // Refuse → flow continue : GAV → jugement, jugement → prison (peine pleine)
      if (isJugement) {
        // Au jugement, refus = peine pleine (pas de réduction)
        const finalDays = record.sentence_days || 1;
        await recordRepo().update({ id: recordId }, {
          judicial_step: 'imprisoned' as JudicialStep,
          lawyer_choice: 'bakchich_refused' as LawyerChoice,
          outcome: 'imprisoned' as JudicialOutcome,
          next_step_at: null,
        });
        try {
          const { PrisonAssignmentService } = await import('./prison-assignment.service');
          await PrisonAssignmentService.assignPrison(playerId, finalDays);
        } catch { /* silent */ }
        return {
          step: 'imprisoned',
          outcome: 'imprisoned',
          flavor: `« Tant pis pour vous. » Le juge prononce la peine pleine : ${finalDays} jour(s).`,
        };
      } else {
        // GAV → transition vers jugement
        const transitionAt = new Date(Date.now() + 30 * 60 * 1000);
        await recordRepo().update({ id: recordId }, {
          judicial_step: 'jugement' as JudicialStep,
          lawyer_choice: 'bakchich_refused' as LawyerChoice,
          next_step_at: transitionAt,
        });
        emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'jugement', next_step_at: transitionAt.toISOString() });
        return {
          step: 'jugement',
          flavor: `Refus du bakchich. Le commissaire prend ça mal : direction le tribunal.`,
        };
      }
    }

    // accepts=true
    const amount = isJugement
      ? Math.round(computeBakchichJugeAmount(ctx.chaleur, ctx.degree, ctx.is_violent) * (2 - mult))
      : Math.round(PHASE7_DEFAULTS.bakchich_gav_amount * (2 - mult));
    const currency: 'infinite_light' | 'infinite_shadow' = 'infinite_shadow';

    const balance = await balancesRepo().findOneBy({ player_id: playerId });
    if (Number(balance?.infinite_shadow ?? 0) < amount) {
      // Fonds insuffisants après tirage → forcer refuse
      return JudicialFlowService.respondToBakchich(playerId, recordId, false);
    }

    await balancesRepo().decrement({ player_id: playerId }, currency, amount);
    await TransactionService.log({
      player_id: playerId, category: 'crime', type: 'out',
      amount, currency,
      description: isJugement ? 'Bakchich juge' : 'Bakchich commissaire',
    });
    await recordRepo().update({ id: recordId }, {
      judicial_step: 'released' as JudicialStep,
      lawyer_choice: 'bakchich_accepted' as LawyerChoice,
      paid_amount: record.paid_amount + amount,
      outcome: 'released_via_bakchich' as JudicialOutcome,
      next_step_at: null,
    });

    const flavor = isJugement
      ? `Le juge empoche, classe le dossier. Tu sors libre (${amount.toLocaleString('fr-FR')} ∞ shadow${stars > 1 ? `, mult avocat ${Math.round((mult - 1) * 100)}%` : ''}).`
      : `Le commissaire encaisse, et te conduit à la sortie. (${amount.toLocaleString('fr-FR')} ∞ shadow)`;
    emitToPlayer(playerId, 'judicial:step-changed', { record_id: recordId, step: 'released', outcome: 'released_via_bakchich' });

    return { step: 'released', outcome: 'released_via_bakchich', cost_paid: amount, flavor };
  }

  /**
   * Au jugement (uniquement), le joueur peut utiliser un item judiciaire :
   *   - Alibi / Jurisprudence : annule incarcération (libéré)
   *   - Vice de procédure : annule jugement, libération aléatoire 5-45 min
   * (Grâce et Appel sont prison-only, pas via cette méthode.)
   */
  static async useItemAtJugement(
    playerId: string,
    recordId: string,
    itemSubtype: 'Alibi' | 'Jurisprudence' | 'Vice de procédure',
  ): Promise<JudicialStepResult> {
    const record = await recordRepo().findOneBy({ id: recordId });
    if (!record) throw new Error('Record introuvable');
    if (record.player_id !== playerId) throw new Error('Record n\'appartient pas au joueur');
    if (record.judicial_step !== 'jugement') {
      throw new Error('Items utilisables uniquement au jugement.');
    }

    const allowed = ['Alibi', 'Jurisprudence', 'Vice de procédure'];
    if (!allowed.includes(itemSubtype)) {
      throw new Error(`Item invalide au jugement: ${itemSubtype}`);
    }

    const { PlayerInventory } = await import('../models/PlayerInventory');
    const invRepo = AppDataSource.getRepository(PlayerInventory);
    const row = await invRepo.findOne({
      where: { player_id: playerId, item_type: 'document', item_subtype: itemSubtype },
    });
    if (!row) throw new Error(`Item « ${itemSubtype} » introuvable dans votre inventaire.`);
    const usesBefore = row.uses_remaining ?? 1;
    if (usesBefore <= 0) {
      await invRepo.delete({ id: row.id });
      throw new Error(`Item « ${itemSubtype} » épuisé.`);
    }

    const usesAfter = usesBefore - 1;
    if (usesAfter <= 0) {
      if (row.quantity > 1) {
        await invRepo.update({ id: row.id }, { quantity: row.quantity - 1, uses_remaining: 1 });
      } else {
        await invRepo.delete({ id: row.id });
      }
    } else {
      await invRepo.update({ id: row.id }, { uses_remaining: usesAfter });
    }

    let flavor: string;
    if (itemSubtype === 'Vice de procédure') {
      // Libération aléatoire 5-45 min
      const minMin = await GameSettingsService.get('judicial.items.vice.release_min_min', PHASE7_DEFAULTS.vice_release_min_minutes);
      const maxMin = await GameSettingsService.get('judicial.items.vice.release_max_min', PHASE7_DEFAULTS.vice_release_max_minutes);
      const delayMin = minMin + Math.random() * (maxMin - minMin);
      const releaseAt = new Date(Date.now() + delayMin * 60 * 1000);
      await healthRepo().update({ player_id: playerId }, { imprisoned_until: releaseAt });
      flavor = `Vice de procédure invoqué. Le juge classe l'affaire. Libération dans ${Math.round(delayMin)} min.`;
    } else {
      // Alibi / Jurisprudence : libération immédiate (sortie du flow)
      flavor = itemSubtype === 'Alibi'
        ? 'Votre avocat présente un alibi béton. Vous sortez libre.'
        : 'Votre avocat invoque une jurisprudence. L\'affaire est classée.';
    }

    await recordRepo().update({ id: recordId }, {
      judicial_step: 'released' as JudicialStep,
      lawyer_choice: 'item_used' as LawyerChoice,
      outcome: 'released_via_item' as JudicialOutcome,
      sentence_avoided_by: itemSubtype,
      next_step_at: null,
    });

    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: 'Item judiciaire utilisé',
        message: flavor,
      }));
    } catch { /* silent */ }

    emitToPlayer(playerId, 'judicial:step-changed', {
      record_id: recordId,
      step: 'released',
      outcome: 'released_via_item',
      item_used: itemSubtype,
    });

    return { step: 'released', outcome: 'released_via_item', flavor };
  }

  /**
   * CRON 60s — gère les transitions automatiques :
   *   - GAV expirée (next_step_at <= now) → bascule en jugement
   *   - Jugement timeout (no action) → applique peine pleine par défaut
   */
  static async processStepTransitions(): Promise<{ transitions: number }> {
    const now = new Date();
    const due = await recordRepo()
      .createQueryBuilder('cr')
      .where('cr.next_step_at IS NOT NULL')
      .andWhere('cr.next_step_at <= :now', { now })
      .andWhere('cr.judicial_step IN (:...steps)', { steps: ['garde_a_vue', 'jugement'] })
      .getMany();

    let transitions = 0;

    for (const rec of due) {
      try {
        if (rec.judicial_step === 'garde_a_vue') {
          // GAV timeout → jugement (30min pour réagir au modal)
          const next = new Date(now.getTime() + 30 * 60 * 1000);
          await recordRepo().update({ id: rec.id }, {
            judicial_step: 'jugement' as JudicialStep,
            next_step_at: next,
          });
          emitToPlayer(rec.player_id, 'judicial:step-changed', {
            record_id: rec.id,
            step: 'jugement',
            next_step_at: next.toISOString(),
            timeout: true,
          });
          transitions++;
        } else if (rec.judicial_step === 'jugement') {
          // Jugement timeout → peine pleine
          await recordRepo().update({ id: rec.id }, {
            judicial_step: 'imprisoned' as JudicialStep,
            outcome: 'imprisoned' as JudicialOutcome,
            next_step_at: null,
          });
          try {
            const { PrisonAssignmentService } = await import('./prison-assignment.service');
            await PrisonAssignmentService.assignPrison(rec.player_id, rec.sentence_days || 1);
          } catch { /* silent */ }
          emitToPlayer(rec.player_id, 'judicial:step-changed', {
            record_id: rec.id,
            step: 'imprisoned',
            timeout: true,
          });
          transitions++;
        }
      } catch (err) {
        console.error('[JudicialFlow] transition error', rec.id, ':', (err as Error).message);
      }
    }

    return { transitions };
  }

  /**
   * Retourne le record actuellement en flow (garde_a_vue ou jugement) pour ce joueur.
   * Un seul flow actif à la fois — garde-fou multi-charges.
   */
  static async getActiveFlowRecord(playerId: string): Promise<CriminalRecord | null> {
    return recordRepo()
      .createQueryBuilder('cr')
      .where('cr.player_id = :pid', { pid: playerId })
      .andWhere('cr.judicial_step IN (:...steps)', { steps: ['garde_a_vue', 'jugement'] })
      .orderBy('cr.crime_date', 'DESC')
      .getOne();
  }

  /**
   * Retourne les records "fine_active" actifs pour un joueur (pour banner UI).
   */
  static async listActiveFines(playerId: string): Promise<CriminalRecord[]> {
    return recordRepo().find({
      where: { player_id: playerId, judicial_step: 'fine_active' as JudicialStep },
      order: { crime_date: 'DESC' },
    });
  }
}
