import { Between } from 'typeorm';
import { AppDataSource } from '../config/database';
import { PoliceUnit, PoliceUnitType, PoliceUnitStatus } from '../models/PoliceUnit';
import { Player } from '../models/Player';
import { PlayerGauges } from '../models/PlayerGauges';
import { GangMember } from '../models/GangMember';
import { haversineDistance } from '../constants/travel-speeds';
import { JudicialService } from './judicial.service';
// audit 15-04-2026 Phase 13.e — heat redirect intelligent sur arrestation gangster
import { GangBalanceService } from './gang-balance.service';

const unitRepo = () => AppDataSource.getRepository(PoliceUnit);
const playerRepo = () => AppDataSource.getRepository(Player);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);

/** In-memory crime scene tracker — BAC/Stups patrol these locations for 24h */
type CrimeCategory = 'drug' | 'other';
interface CrimeScene { lat: number; lon: number; timestamp: number; category: CrimeCategory; }
const recentCrimeScenes: CrimeScene[] = [];

function addCrimeScene(lat: number, lon: number, crimeType?: string) {
  const isDrug = crimeType === 'trafic_drogue';
  recentCrimeScenes.push({ lat, lon, timestamp: Date.now(), category: isDrug ? 'drug' : 'other' });
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
  while (recentCrimeScenes.length > 0 && recentCrimeScenes[0].timestamp < cutoff) {
    recentCrimeScenes.shift();
  }
}

function getCrimeScenesNear(centerLat: number, centerLon: number, radiusKm: number, category?: CrimeCategory): CrimeScene[] {
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
  return recentCrimeScenes.filter(s =>
    s.timestamp >= cutoff &&
    (!category || s.category === category) &&
    haversineDistance(centerLat, centerLon, s.lat, s.lon) <= radiusKm
  );
}

/**
 * Police unit templates for generation around a territory.
 *
 * Heat 0-19: patrouilles se succedent (3 unites actives)
 * Heat 20-38: 3 equipes en meme temps
 * Heat 40-59: 6 equipes
 * Heat 60-94: toutes (18 unites)
 * Heat 95-99: renforts doubles
 * Heat 100: GIGN
 */

interface UnitTemplate {
  type: PoliceUnitType;
  agents_count: number;
  weapons: string[];
  vision_km: number;
  radio_km: number;
  speed_kmh: number;
  heat_threshold: number;
}

const UNIT_TEMPLATES: UnitTemplate[] = [
  // Police Municipale + Nationale : 3 voitures (x3 agents)
  { type: 'patrol_car', agents_count: 3, weapons: ['Pistolet 9mm', 'Pistolet 9mm', 'Pistolet 9mm'], vision_km: 0.2, radio_km: 5, speed_kmh: 80, heat_threshold: 0 },
  { type: 'patrol_car', agents_count: 3, weapons: ['Pistolet 9mm', 'Pistolet 9mm', 'Fusil Pompe'], vision_km: 0.2, radio_km: 5, speed_kmh: 80, heat_threshold: 20 },
  { type: 'patrol_car', agents_count: 3, weapons: ['Pistolet 9mm', 'Pistolet 9mm', 'Pistolet 9mm'], vision_km: 0.2, radio_km: 5, speed_kmh: 80, heat_threshold: 40 },
  // 6 motos (x1 agent)
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 0 },
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 0 },
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 20 },
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 40 },
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 60 },
  { type: 'patrol_moto', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 2, speed_kmh: 120, heat_threshold: 60 },
  // 9 agents a pied
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 0 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 0 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 20 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 20 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 40 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 40 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 60 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 60 },
  { type: 'patrol_foot', agents_count: 1, weapons: ['Pistolet 9mm'], vision_km: 0.2, radio_km: 1, speed_kmh: 5, heat_threshold: 60 },
  // BAC : 4 agents civil, voiture rapide banalisee
  { type: 'bac', agents_count: 4, weapons: ['Pistolet 9mm', 'Pistolet 9mm', 'Pistolet 9mm', 'Fusil Pompe'], vision_km: 0.5, radio_km: 5, speed_kmh: 120, heat_threshold: 40 },
  // Brigade Stups : 4 agents civil, voiture rapide banalisee
  { type: 'stups', agents_count: 4, weapons: ['Revolver .38', 'Revolver .38', 'Revolver .38', 'AK-47'], vision_km: 0.5, radio_km: 5, speed_kmh: 100, heat_threshold: 60 },
  // GIGN : 2 camions de 9 + 1 helicoptere de 9 = 27 agents
  { type: 'gign_truck', agents_count: 9, weapons: ['M16', 'M16', 'M16', 'M16', 'M16', 'Sniper', 'Fusil Pompe', 'AK-47', 'AK-47'], vision_km: 0.5, radio_km: 10, speed_kmh: 90, heat_threshold: 100 },
  { type: 'gign_truck', agents_count: 9, weapons: ['M16', 'M16', 'M16', 'M16', 'M16', 'Sniper', 'Fusil Pompe', 'AK-47', 'AK-47'], vision_km: 0.5, radio_km: 10, speed_kmh: 90, heat_threshold: 100 },
  { type: 'gign_helicopter', agents_count: 9, weapons: ['M16', 'M16', 'M16', 'M16', 'M16', 'Sniper', 'Sniper', 'AK-47', 'AK-47'], vision_km: 0.5, radio_km: 10, speed_kmh: 200, heat_threshold: 100 },
];

export class PolicePatrolService {

  /**
   * Generate police patrols for a player's territory.
   * Called once when a territory is initialized.
   */
  static async generatePatrols(playerId: string): Promise<number> {
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player?.start_lat || !player?.start_lon) return 0;

    let created = 0;
    for (const tmpl of UNIT_TEMPLATES) {
      // Random position within patrol radius (~0.98km = 3km2 area)
      const angle = Math.random() * Math.PI * 2;
      const r = Math.random() * 0.009; // ~1km
      const lat = Number(player.start_lat) + r * Math.cos(angle);
      const lon = Number(player.start_lon) + r * Math.sin(angle) / Math.cos(Number(player.start_lat) * Math.PI / 180);

      // Phase 4 bis markers (2026-05-07) — branche hiérarchique pour les
      // patrouilles standard. Random 50/50 mun/nat. Les autres types
      // (bac/stups/gign/fbi/dea) gardent branch=null (sémantique propre).
      const isPatrolUnit = tmpl.type === 'patrol_foot' || tmpl.type === 'patrol_moto' || tmpl.type === 'patrol_car';
      const branch = isPatrolUnit ? (Math.random() < 0.5 ? 'municipale' : 'nationale') : null;

      const unit = unitRepo().create({
        type: tmpl.type,
        branch,
        agents_count: tmpl.agents_count,
        weapons: tmpl.weapons,
        vision_km: tmpl.vision_km,
        radio_km: tmpl.radio_km,
        speed_kmh: tmpl.speed_kmh,
        patrol_center_lat: Number(player.start_lat),
        patrol_center_lon: Number(player.start_lon),
        patrol_radius_km: 0.98,
        current_lat: lat,
        current_lon: lon,
        status: 'patrolling',
        heat_threshold: tmpl.heat_threshold,
        is_active: tmpl.heat_threshold === 0, // Only base patrols active initially
      });
      await unitRepo().save(unit);
      created++;
    }
    return created;
  }

  /**
   * Update police activity based on player heat levels.
   * Called periodically (every 60s).
   * Activates/deactivates units based on heat thresholds.
   */
  static async updatePatrolActivity(): Promise<{ activated: number; deactivated: number }> {
    const allUnits = await unitRepo().find();
    if (allUnits.length === 0) return { activated: 0, deactivated: 0 };

    // Get all player heat levels
    const allGauges = await gaugesRepo().find();
    const heatMap = new Map<string, number>();
    for (const g of allGauges) {
      heatMap.set(g.player_id, Number(g.chaleur));
    }

    // Group units by patrol center (approximate to territory)
    // For each unit, find the nearest player and check heat
    let activated = 0, deactivated = 0;

    // Get all players with territories
    const players = await playerRepo().find({
      where: { onboarding_completed: true },
      select: ['id', 'start_lat', 'start_lon'],
    });

    // Phase 9 (2026-04-20) — préchargement bribes actifs pour les joueurs proches
    // (appel lazy via ForceBribeService dans la boucle)
    const { ForceBribeService } = await import('./force-bribe.service');

    for (const unit of allUnits) {
      // Find nearest player territory
      let nearestHeat = 0;
      let nearestPlayerId: string | null = null;
      for (const p of players) {
        if (!p.start_lat || !p.start_lon) continue;
        const dist = haversineDistance(
          Number(unit.patrol_center_lat), Number(unit.patrol_center_lon),
          Number(p.start_lat), Number(p.start_lon),
        );
        if (dist < 2) { // Within 2km of territory
          const heat = heatMap.get(p.id) ?? 0;
          if (heat > nearestHeat) {
            nearestHeat = heat;
            nearestPlayerId = p.id;
          }
        }
      }

      // Phase 9 (2026-04-20) — bribe de la force associée à cette unité neutralise le heat
      // (police/bac/stups → 'police' ; gign_* → 'gign').
      const isGign = unit.type === 'gign_truck' || unit.type === 'gign_helicopter';
      const bribeForce = isGign ? 'gign' : 'police';
      let effectiveHeat = nearestHeat;
      if (nearestPlayerId) {
        const bribed = await ForceBribeService.isBribedActive(nearestPlayerId, bribeForce as any);
        if (bribed) effectiveHeat = 0;
      }

      // Heat 95-99 : renforts doubles — toutes unites actives sauf GIGN
      // Heat 100 : GIGN deploye
      const shouldBeActive = isGign
        ? effectiveHeat >= 100
        : (effectiveHeat >= 95 || effectiveHeat >= unit.heat_threshold);

      // Phase 8.5 (2026-04-29) — Skip respawn GIGN si cooldown 48h actif
      // pour ce player (toutes ses unités GIGN ont été tuées récemment).
      // Aligné sur CartelHeatService.GIGN_COOLDOWN_HOURS = 48.
      if (shouldBeActive && !unit.is_active && isGign && nearestPlayerId) {
        const { PoliceGignCombatService } = await import('./police-gign-combat.service');
        const cooldownActive = await PoliceGignCombatService.isRespawnCooldownActive(nearestPlayerId);
        if (cooldownActive) {
          // Skip respawn cette unité — cooldown actif
          continue;
        }
      }

      if (shouldBeActive && !unit.is_active) {
        unit.is_active = true;
        unit.status = 'patrolling';
        // Phase 8.5 — Refill agents_count à la valeur seed initiale au respawn
        if (isGign && unit.agents_count <= 0) {
          unit.agents_count = unit.type === 'gign_helicopter' ? 9 : 9;
        }

        // Phase 8.5d (2026-04-29) — GIGN délai 60s entre spawn et premier
        // dommage territoire (spec user : laisser fuir/défendre).
        // engageDefenders skip combat si now < estimated_arrival_at.
        if (isGign && nearestPlayerId) {
          const { GameSettingsService } = await import('./game-settings.service');
          const delayS = await GameSettingsService.get<number>('gign.spawn_to_attack_delay_seconds', 60);
          unit.estimated_arrival_at = new Date(Date.now() + delayS * 1000);
        }

        await unitRepo().save(unit);
        activated++;

        // Phase 8.5d (2026-04-29) — Notification "Coup de fil anonyme"
        // au spawn GIGN (premier unit qui s'active sur ce player). On
        // dédoublonne en envoyant 1 notif unique par player target par
        // session de raid (les unités spawnent en cluster en quelques
        // secondes — si déjà notifié pour ce player, skip).
        if (isGign && nearestPlayerId) {
          await PolicePatrolService.notifyGignSpawnIfNeeded(nearestPlayerId);
        }
      } else if (!shouldBeActive && unit.is_active && unit.heat_threshold > 0) {
        unit.is_active = false;
        unit.status = 'idle';
        unit.estimated_arrival_at = null;
        await unitRepo().save(unit);
        deactivated++;
      }
    }

    // GIGN assault: at heat 100, GIGN engages defenders FIRST then territory
    // Phase 8.5 (2026-04-29) — combat avec gangsters joueur + player avant
    // damage territoire. Si défense KO → GIGN passe au territoire (-10 HP/unit).
    // Si HP territoire = 0 → assignPrison(targetPlayerId, 8 jours).
    // Si TOUTES les unités GIGN sont tuées → -5 chaleur + cooldown 48h respawn.
    if (activated > 0 || allUnits.some(u => u.is_active)) {
      const { PoliceGignCombatService } = await import('./police-gign-combat.service');
      const { GameSettingsService } = await import('./game-settings.service');
      const { TerritoryService } = await import('./territory.service');

      const damagePerAttack = await GameSettingsService.get<number>('gign.combat.damage_per_attack', 10);
      const playerTargetIds = new Set<string>();

      for (const unit of allUnits) {
        if (!unit.is_active) continue;
        if (unit.type !== 'gign_truck' && unit.type !== 'gign_helicopter') continue;

        // Find the player whose territory this unit patrols
        for (const p of players) {
          if (!p.start_lat || !p.start_lon) continue;
          const dist = haversineDistance(
            Number(unit.patrol_center_lat), Number(unit.patrol_center_lon),
            Number(p.start_lat), Number(p.start_lon),
          );
          if (dist >= 2) continue;
          const heat = heatMap.get(p.id) ?? 0;
          if (heat < 100) continue;

          playerTargetIds.add(p.id);

          // Reload unit fresh (might have been mutated by previous engageDefenders)
          const freshUnit = await unitRepo().findOneBy({ id: unit.id });
          if (!freshUnit || !freshUnit.is_active) break;

          // 1. Combat vs défenseurs
          const engageResult = await PoliceGignCombatService.engageDefenders(freshUnit, p.id);

          // 2. Si voie libre (pas de défenseurs ou défenseurs vaincus) → damage territoire
          if (!engageResult.defenders_present || !engageResult.defenders_won) {
            const dmg = await TerritoryService.damageTerritory(p.id, damagePerAttack);
            if (dmg.conquered) {
              // Phase 17 (2026-05-04) — Le GIGN ne DÉTRUIT plus le territoire,
              // il le GÈLE pendant 12h (consigne user verbatim).
              // Le territoire reste intact, mais aucun ordre gang ne peut
              // partir tant que territory_frozen_until > NOW.
              // damageTerritory a set territory_destroyed=true à HP=0, on
              // remplace par freezeTerritory qui restore HP=1000 et set
              // frozen_until = NOW + 12h.
              await TerritoryService.freezeTerritory(p.id, 12);
              // L'arrestation 8 jours (ou pending hôpital) reste appliquée
              // séparément via onTerritoryDestroyed qui gère la peine —
              // c'est une logique distincte du gel territoire.
              await PoliceGignCombatService.onTerritoryDestroyed(p.id);
            }
          }
          // Si défenseurs ont gagné → unit GIGN affaiblie/morte (déjà géré par engageDefenders)
          break; // 1 unit ne cible qu'1 player par tick
        }
      }

      // Après tous les combats : check si toutes les unités GIGN sont mortes
      // pour chaque player ciblé (cooldown 48h respawn + bonus -5 chaleur).
      for (const targetId of playerTargetIds) {
        await PoliceGignCombatService.checkAllUnitsKilledForPlayer(targetId);
      }
    }

    return { activated, deactivated };
  }

  /**
   * Phase 8.5d (2026-04-29) — Crée la notif "Coup de fil anonyme" au spawn
   * GIGN. Dédoublonne via WHERE NOT EXISTS sur les 2 dernières minutes
   * (les unités spawnent en cluster à quelques secondes d'intervalle).
   * Émet aussi WS event 'gign:incoming' pour countdown HUD frontend.
   */
  private static async notifyGignSpawnIfNeeded(targetPlayerId: string): Promise<void> {
    const { Notification } = await import('../models/Notification');
    const { GameSettingsService } = await import('./game-settings.service');
    const { emitToPlayer } = await import('../gateways/map.gateway');

    const notifRepo = AppDataSource.getRepository(Notification);

    // Dédoublonnage : si une notif "GIGN rapplique" existe < 2 min, skip
    const twoMinAgo = new Date(Date.now() - 2 * 60 * 1000);
    const existing = await notifRepo
      .createQueryBuilder('n')
      .where('n.player_id = :pid', { pid: targetPlayerId })
      .andWhere("n.title = 'Coup de fil anonyme'")
      .andWhere('n.created_at > :since', { since: twoMinAgo })
      .getOne();
    if (existing) return;

    const delayS = await GameSettingsService.get<number>('gign.spawn_to_attack_delay_seconds', 60);
    try {
      await notifRepo.save(notifRepo.create({
        player_id: targetPlayerId,
        type: 'system',
        title: 'Coup de fil anonyme',
        message: `Le GIGN rapplique. Arrivée estimée dans ${delayS} secondes. Fuyez ou ramenez vos défenseurs.`,
      }));
    } catch { /* silent */ }

    emitToPlayer(targetPlayerId, 'gign:incoming', {
      delay_seconds: delayS,
      arrival_at: new Date(Date.now() + delayS * 1000).toISOString(),
    });
  }

  /**
   * Move patrolling units randomly within their patrol zone.
   * Called periodically (every 30s).
   */
  static async movePatrols(): Promise<number> {
    const activeUnits = await unitRepo().find({
      where: { is_active: true, status: 'patrolling' as PoliceUnitStatus },
    });

    let moved = 0;
    for (const unit of activeUnits) {
      if (unit.current_lat === null || unit.current_lon === null) continue;

      let newLat: number, newLon: number;

      if (unit.type === 'stups' || unit.type === 'bac') {
        // Stups: only drug crimes. BAC: only non-drug crimes.
        const crimeFilter: CrimeCategory = unit.type === 'stups' ? 'drug' : 'other';
        const scenes = getCrimeScenesNear(
          Number(unit.patrol_center_lat), Number(unit.patrol_center_lon), 20, crimeFilter,
        );
        const maxStep = unit.speed_kmh * (30 / 3600);
        const stepDeg = maxStep / 111;
        if (scenes.length > 0) {
          // Move toward the nearest crime scene
          let nearest = scenes[0], nearestDist = Infinity;
          for (const s of scenes) {
            const d = haversineDistance(Number(unit.current_lat), Number(unit.current_lon), s.lat, s.lon);
            if (d < nearestDist) { nearest = s; nearestDist = d; }
          }
          const dLat = nearest.lat - Number(unit.current_lat);
          const dLon = nearest.lon - Number(unit.current_lon);
          const dist = Math.sqrt(dLat * dLat + dLon * dLon);
          if (dist > 0.0001) {
            newLat = Number(unit.current_lat) + stepDeg * (dLat / dist);
            newLon = Number(unit.current_lon) + stepDeg * (dLon / dist) / Math.cos(Number(unit.current_lat) * Math.PI / 180);
          } else {
            // Already at scene — random patrol nearby
            const a = Math.random() * Math.PI * 2;
            newLat = Number(unit.current_lat) + stepDeg * 0.3 * Math.cos(a);
            newLon = Number(unit.current_lon) + stepDeg * 0.3 * Math.sin(a) / Math.cos(Number(unit.current_lat) * Math.PI / 180);
          }
        } else {
          // No relevant crimes — BAC/Stups stay idle (don't move)
          continue;
        }
      } else {
        // Standard patrol: random walk
        const angle = Math.random() * Math.PI * 2;
        const maxStep = unit.speed_kmh * (30 / 3600);
        const step = Math.random() * maxStep;
        const stepDeg = step / 111;
        newLat = Number(unit.current_lat) + stepDeg * Math.cos(angle);
        newLon = Number(unit.current_lon) + stepDeg * Math.sin(angle) / Math.cos(Number(unit.current_lat) * Math.PI / 180);
      }

      // Clamp to patrol radius
      const distFromCenter = haversineDistance(
        Number(unit.patrol_center_lat), Number(unit.patrol_center_lon),
        newLat, newLon,
      );

      if (distFromCenter <= Number(unit.patrol_radius_km)) {
        unit.current_lat = newLat;
        unit.current_lon = newLon;
        await unitRepo().save(unit);
        moved++;
      }

      // Check if any gangster is in vision range — react based on owner's heat
      const nearbyGangsters = await gangMemberRepo().find({
        where: {
          current_lat: Between(Number(unit.current_lat) - 0.003, Number(unit.current_lat) + 0.003) as any,
          current_lon: Between(Number(unit.current_lon) - 0.004, Number(unit.current_lon) + 0.004) as any,
        },
      });
      for (const gm of nearbyGangsters) {
        if (!gm.current_lat || !gm.current_lon || gm.isHospitalized) continue;
        const gmDist = haversineDistance(
          Number(unit.current_lat), Number(unit.current_lon),
          Number(gm.current_lat), Number(gm.current_lon),
        );
        // Gangster sees police at 1km
        if (gmDist > 1.0) continue;

        // Check owner's heat
        const ownerGauges = await gaugesRepo().findOneBy({ player_id: gm.player_id });
        const ownerHeat = Number(ownerGauges?.chaleur ?? 0);

        if (ownerHeat >= 80 && gmDist <= Number(unit.vision_km)) {
          // Heat >= 80 + police sees gangster → engage (police tries arrest)
          try {
            await JudicialService.registerCrimeAndMaybeConvict(gm.player_id, {
              crime_type: 'agression' as any,
              description: 'Gangster ouvre le feu sur la police',
              is_violent: true,
              arrest_probability: 0.5,
              police_risk: 50,
            });
            // audit 15-04-2026 Phase 13.e : heat redirect intelligent.
            // Quand un gangster est arrete, on evalue la probabilite qu'il balance
            // son patron (talk_chance) et on applique les effets en cascade.
            try {
              await GangBalanceService.handleArrest(gm.gang_id, gm.player_id, {
                crime_type: 'agression',
                description: `Gangster interpelle par ${unit.type}`,
                is_violent: true,
              });
            } catch (balErr) {
              // Balance service error is non-fatal — log and continue
              console.error('[PolicePatrol] GangBalance error:', (balErr as Error).message);
            }
          } catch {}
        } else if (ownerHeat < 80 && !gm.in_transit) {
          // Heat < 80 → gangster flees (move away from police)
          const fleeAngle = Math.atan2(
            Number(gm.current_lat) - Number(unit.current_lat),
            Number(gm.current_lon) - Number(unit.current_lon),
          );
          const fleeDist = 0.005; // ~500m away
          const newGmLat = Number(gm.current_lat) + fleeDist * Math.sin(fleeAngle);
          const newGmLon = Number(gm.current_lon) + fleeDist * Math.cos(fleeAngle);
          await gangMemberRepo().update(
            { gang_id: gm.gang_id, player_id: gm.player_id },
            { current_lat: newGmLat, current_lon: newGmLon },
          );
        }
      }
    }

    return moved;
  }

  /**
   * Check if any active police unit can see a crime at given coordinates.
   * If yes, dispatch closest unit to investigate.
   * Returns true if crime was detected by police.
   */
  static async detectCrime(crimeLat: number, crimeLon: number, crimeType?: string): Promise<boolean> {
    // Record crime scene for BAC/Stups patrols (24h memory)
    addCrimeScene(crimeLat, crimeLon, crimeType);

    const activeUnits = await unitRepo().find({
      where: { is_active: true },
    });

    let detected = false;
    for (const unit of activeUnits) {
      if (unit.current_lat === null || unit.current_lon === null) continue;
      if (unit.status === 'idle') continue;

      const dist = haversineDistance(
        Number(unit.current_lat), Number(unit.current_lon),
        crimeLat, crimeLon,
      );

      // Direct vision detection
      if (dist <= Number(unit.vision_km)) {
        detected = true;
        // Unit engages directly
        if (unit.status === 'patrolling') {
          unit.status = 'responding';
          unit.dest_lat = crimeLat;
          unit.dest_lon = crimeLon;
          unit.eta = new Date(Date.now() + (dist / unit.speed_kmh) * 3600 * 1000);
          await unitRepo().save(unit);
        }
      }
      // Radio detection (within radio range, cars only respond within 5km)
      else if (dist <= Number(unit.radio_km) && unit.status === 'patrolling') {
        // Only car/moto units respond to radio
        if (['patrol_car', 'patrol_moto', 'bac', 'stups'].includes(unit.type)) {
          unit.status = 'responding';
          unit.dest_lat = crimeLat;
          unit.dest_lon = crimeLon;
          const travelTime = (dist / unit.speed_kmh) * 3600 * 1000;
          unit.eta = new Date(Date.now() + travelTime);
          await unitRepo().save(unit);
          detected = true;
        }
      }
    }

    return detected;
  }

  /**
   * Resolve responding units that have arrived.
   * Units that arrive at crime scene start inspecting (5min).
   * Called every 30s.
   */
  static async resolveResponding(): Promise<number> {
    const now = new Date();
    const respondingUnits = await unitRepo().find({
      where: { status: 'responding' as PoliceUnitStatus, is_active: true },
    });

    let resolved = 0;
    for (const unit of respondingUnits) {
      if (!unit.eta || now < unit.eta) continue;

      // Arrived at scene — check if a criminal player is still nearby
      unit.current_lat = unit.dest_lat;
      unit.current_lon = unit.dest_lon;

      // Look for players with heat >= 40 within vision range
      const nearbyPlayers = await playerRepo().find({
        where: { in_transit: false, onboarding_completed: true },
      });
      let caughtPlayer = false;
      for (const p of nearbyPlayers) {
        if (!p.current_lat || !p.current_lon) continue;
        const pHeat = (await gaugesRepo().findOneBy({ player_id: p.id }))?.chaleur ?? 0;
        if (Number(pHeat) < 40) continue;
        const d = haversineDistance(Number(unit.current_lat), Number(unit.current_lon), Number(p.current_lat), Number(p.current_lon));
        if (d <= Number(unit.vision_km)) {
          // Player spotted — pursue and arrest
          try {
            await JudicialService.registerCrimeAndMaybeConvict(p.id, {
              crime_type: 'vol' as any,
              description: `Interpellation par ${unit.type === 'bac' ? 'la BAC' : unit.type === 'stups' ? 'les Stups' : 'une patrouille'}`,
              is_violent: false,
              arrest_probability: 0.7,
              police_risk: 30,
            });
            caughtPlayer = true;
          } catch {}
        }
      }

      // Start inspection (5min)
      unit.status = 'inspecting';
      unit.eta = new Date(now.getTime() + 5 * 60 * 1000);
      await unitRepo().save(unit);
      resolved++;
    }

    // Also resolve inspecting units (go back to patrol after 5min)
    const inspectingUnits = await unitRepo().find({
      where: { status: 'inspecting' as PoliceUnitStatus, is_active: true },
    });
    for (const unit of inspectingUnits) {
      if (!unit.eta || now < unit.eta) continue;

      // Foot and moto patrols stay near crime scene for 30min
      if (['patrol_foot', 'patrol_moto'].includes(unit.type)) {
        // Continue patrolling near crime scene for 30min
        unit.status = 'patrolling';
        unit.dest_lat = null;
        unit.dest_lon = null;
        unit.eta = null;
      } else {
        // Cars return to patrol
        unit.status = 'patrolling';
        unit.dest_lat = null;
        unit.dest_lon = null;
        unit.eta = null;
      }
      await unitRepo().save(unit);
      resolved++;
    }

    return resolved;
  }
}
