/**
 * Phase 8.5 (2026-04-29) — Combat GIGN vs défenseurs (gangsters joueur + joueur sur place).
 *
 * Spec user (2026-04-29) :
 *   - GIGN units arrivent vers le territoire d'un joueur à chaleur 100
 *   - Combat AUTO vs défenseurs (gangsters du gang du player + player s'il est sur place)
 *   - Si défenseurs vivants → GIGN ne peut pas attaquer le territoire (voie bloquée)
 *   - Si défenseurs KO → GIGN attaque le territoire (-10 HP/attaque/unité)
 *   - HP territoire = 0 → joueur prison 8 jours (assignPrison)
 *   - Si TOUTES les unités GIGN du raid de CE player sont tuées :
 *     • -5 chaleur sur le player
 *     • last_gign_killed_at = now → cooldown 48h respawn (spécifique player, pas global)
 *       (aligné Phase 8.5 audit 29-04-2026 sur CartelHeatService.GIGN_COOLDOWN_HOURS=48)
 *   - Si joueur mort en combat → hôpital → prison hook (Étape 2.4 séparée)
 *
 * Pas d'identité player_id pour les agents GIGN : on travaille au niveau de
 * `police_units.agents_count`. Quand un agent "tombe" → decrement counter.
 * Quand `agents_count <= 0` → unit `is_active=false`, `status='idle'`.
 *
 * Tous les paramètres sont éditables via game_settings.gign.combat.* sans
 * redéploiement (cf migration 058).
 */
import { AppDataSource } from '../config/database';
import { GangMember } from '../models/GangMember';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerGauges } from '../models/PlayerGauges';
import { PoliceUnit } from '../models/PoliceUnit';
import { Notification } from '../models/Notification';
import { GroupCombatService, type CombatantDetail } from './group-combat.service';
import { GameSettingsService } from './game-settings.service';
import { emitToPlayer } from '../gateways/map.gateway';

const gmRepo = () => AppDataSource.getRepository(GangMember);
const phRepo = () => AppDataSource.getRepository(PlayerHealth);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const unitRepo = () => AppDataSource.getRepository(PoliceUnit);
const notifRepo = () => AppDataSource.getRepository(Notification);

// Defaults (overridables via game_settings)
const GIGN_DEFAULTS = {
  damage_per_attack: 10,
  sentence_days: 8,
  heat_reduction_on_kill_all: 5,
  respawn_cooldown_hours: 48,
  agent_attack: 30,
  agent_defense: 20,
  agent_grade: 5,
  agent_skill: 80,
};

export interface GignEngageResult {
  defenders_present: boolean;
  defenders_won: boolean;
  defender_casualties_player_ids: string[];
  gign_agent_loss: number;
  gign_unit_eliminated: boolean;
  attack_score: number;
  defense_score: number;
}

export class PoliceGignCombatService {
  /**
   * Score d'attaque de l'unité GIGN courante.
   * agents_count × grade × attack × (1 + skill/100)
   */
  static async gignAttackScore(unit: PoliceUnit): Promise<number> {
    const grade = await GameSettingsService.get<number>('gign.combat.agent_grade', GIGN_DEFAULTS.agent_grade);
    const attack = await GameSettingsService.get<number>('gign.combat.agent_attack', GIGN_DEFAULTS.agent_attack);
    const skill = await GameSettingsService.get<number>('gign.combat.agent_skill', GIGN_DEFAULTS.agent_skill);
    return unit.agents_count * grade * attack * (1 + skill / 100);
  }

  /**
   * Engage un combat entre une unité GIGN et les défenseurs du player target.
   * Défenseurs = tous les gangsters du gang du target_player_id + le player
   * lui-même (s'il n'est pas hospitalisé/imprisoned, filtré automatiquement
   * par GroupCombatService.loadCombatant).
   *
   * Retourne :
   *   - defenders_present : false si aucun défenseur valide → caller passe au damage territoire
   *   - defenders_won : true si défenseurs survivent (ratio defense > attack × 1.2)
   *   - gign_unit_eliminated : true si agents_count tombe ≤ 0 → unit deactivated
   *
   * Side effects :
   *   - Casualties défenseurs → hospitalized_until = now + 24h (via GroupCombatService.applyCasualties)
   *   - Casualties GIGN → unit.agents_count décrémenté (Math.ceil sur ratio inverse)
   */
  static async engageDefenders(
    unit: PoliceUnit,
    targetPlayerId: string,
  ): Promise<GignEngageResult> {
    // Phase 8.5d (2026-04-29) — Skip combat tant que GIGN est "en route"
    // (estimated_arrival_at futur). Spec user : 60s entre spawn et premier
    // dommage territoire pour laisser fuir/défendre.
    if (unit.estimated_arrival_at && unit.estimated_arrival_at > new Date()) {
      return {
        defenders_present: false,
        defenders_won: false,
        defender_casualties_player_ids: [],
        gign_agent_loss: 0,
        gign_unit_eliminated: false,
        attack_score: 0,
        defense_score: 0,
      };
    }

    // 1. Trouver les défenseurs : gangsters du gang du player + player lui-même
    const defenderIds = new Set<string>();
    defenderIds.add(targetPlayerId);

    const gm = await gmRepo().findOne({ where: { player_id: targetPlayerId } });
    if (gm?.gang_id) {
      const peers = await gmRepo().find({ where: { gang_id: gm.gang_id } });
      for (const p of peers) defenderIds.add(p.player_id);
    }

    // 2. Charger combatants (filtrage hospitalized/imprisoned auto)
    const defenders = await GroupCombatService.loadTeam(Array.from(defenderIds));
    if (defenders.length === 0) {
      return {
        defenders_present: false,
        defenders_won: false,
        defender_casualties_player_ids: [],
        gign_agent_loss: 0,
        gign_unit_eliminated: false,
        attack_score: 0,
        defense_score: 0,
      };
    }

    // 3. Compute scores
    const attackScore = await PoliceGignCombatService.gignAttackScore(unit);
    const defenseScore = GroupCombatService.scoreTeamPublic(defenders, 'defense');

    if (attackScore > defenseScore * 1.2) {
      // GIGN gagne — défenseurs hospitalisés
      const ratio = attackScore / Math.max(1, defenseScore);
      // Casualties défenseurs : Math.round(losers.length × (ratio - 1) × 0.3)
      const casualtyCount = Math.min(defenders.length, Math.max(0, Math.round(defenders.length * (ratio - 1) * 0.3)));
      const casualtyDefenders = defenders.slice(0, casualtyCount);
      const casualtyIds = casualtyDefenders.map(d => d.player_id);

      // Phase 8.5d (2026-04-29) — Hospitalize via HospitalService qui :
      //   - Set hospitalized_until + physical_health=5
      //   - Déplace GPS au + proche hôpital (current_lat/lon + hospital_lat/lon)
      //   - Reason='gign_combat' → flavor "Ça a chauffé grave..."
      //   - Skip + heal si player owns cet hôpital (évasion auto)
      const { HospitalService } = await import('./hospital.service');
      for (const id of casualtyIds) {
        try {
          await HospitalService.hospitalize(id, 'gign_combat', 24);
        } catch (err) {
          // Fallback : set minimal hospitalized_until
          await phRepo().update(
            { player_id: id },
            { hospitalized_until: new Date(Date.now() + 24 * 3600 * 1000) },
          );
        }
      }

      // Notif au player target
      try {
        await notifRepo().save(notifRepo().create({
          player_id: targetPlayerId,
          type: 'system',
          title: 'Combat GIGN — défense brisée',
          message: `Le GIGN a percé ta défense. ${casualtyIds.length} défenseur(s) à l'hôpital. Le territoire est exposé.`,
        }));
      } catch { /* silent */ }

      return {
        defenders_present: true,
        defenders_won: false,
        defender_casualties_player_ids: casualtyIds,
        gign_agent_loss: 0,
        gign_unit_eliminated: false,
        attack_score: attackScore,
        defense_score: defenseScore,
      };
    }

    // Défenseurs résistent — GIGN unit prend des pertes
    const ratio = defenseScore / Math.max(1, attackScore);
    const lossCount = Math.min(unit.agents_count, Math.max(1, Math.ceil(unit.agents_count * (ratio - 1) * 0.5)));
    const newAgentsCount = unit.agents_count - lossCount;
    const eliminated = newAgentsCount <= 0;

    await unitRepo().update(
      { id: unit.id },
      {
        agents_count: Math.max(0, newAgentsCount),
        is_active: !eliminated,
        status: eliminated ? ('idle' as any) : unit.status,
      },
    );

    try {
      await notifRepo().save(notifRepo().create({
        player_id: targetPlayerId,
        type: 'system',
        title: 'GIGN repoussé !',
        message: eliminated
          ? `Tes hommes ont éliminé une unité GIGN entière (${lossCount} agents). Solide.`
          : `Tes hommes ont touché une unité GIGN (${lossCount} agents abattus). Elle continue cependant.`,
      }));
    } catch { /* silent */ }

    return {
      defenders_present: true,
      defenders_won: true,
      defender_casualties_player_ids: [],
      gign_agent_loss: lossCount,
      gign_unit_eliminated: eliminated,
      attack_score: attackScore,
      defense_score: defenseScore,
    };
  }

  /**
   * Hook : appelé après chaque tour de combat GIGN sur ce player. Vérifie si
   * TOUTES les unités GIGN actuellement actives qui ciblent ce player ont
   * été éliminées. Si oui → -5 chaleur + last_gign_killed_at + cooldown 48h
   * respawn spécifique au player.
   */
  static async checkAllUnitsKilledForPlayer(targetPlayerId: string): Promise<{ allKilled: boolean }> {
    // On considère qu'une unité GIGN cible ce player si elle est dans son
    // territoire (proximity check fait dans police-patrol). Ici on regarde
    // simplement : reste-t-il des units GIGN actives ?
    // Note : on ne peut pas trivialement filtrer par target_player_id (les
    // GIGN units sont seedées au niveau territory, pas par player). On utilise
    // ici un proxy : si toutes les units GIGN actives ont agents_count=0 OR
    // is_active=false, on considère le raid terminé.
    const allGignUnits = await unitRepo().find({
      where: [
        { type: 'gign_truck' as any },
        { type: 'gign_helicopter' as any },
      ],
    });
    const stillActive = allGignUnits.filter(u => u.is_active && u.agents_count > 0);

    if (stillActive.length > 0) {
      return { allKilled: false };
    }

    // Toutes les unités sont éliminées → bonus player
    const heatReduction = await GameSettingsService.get<number>(
      'gign.combat.heat_reduction_on_kill_all',
      GIGN_DEFAULTS.heat_reduction_on_kill_all,
    );

    await gaugesRepo()
      .createQueryBuilder()
      .update()
      .set({ chaleur: () => `GREATEST(0, chaleur - ${heatReduction})` })
      .where('player_id = :pid', { pid: targetPlayerId })
      .execute();

    await phRepo().update(
      { player_id: targetPlayerId },
      { last_gign_killed_at: new Date() },
    );

    try {
      await notifRepo().save(notifRepo().create({
        player_id: targetPlayerId,
        type: 'system',
        title: 'GIGN anéanti',
        message: `Toutes les unités GIGN ont été éliminées. Chaleur −${heatReduction}. Cooldown respawn 48h.`,
      }));
    } catch { /* silent */ }

    emitToPlayer(targetPlayerId, 'gign:all-units-killed', { heat_reduction: heatReduction });

    return { allKilled: true };
  }

  /**
   * Hook : appelé quand HP territoire passe à 0 sous attaques GIGN.
   * → assignPrison(targetPlayerId, 8 jours) via PrisonAssignmentService.
   * Note : si player KO en combat (hospitalized_until > now), assignPrison
   * sera appelé au sortie de l'hôpital via Étape 2.4 (hook séparé).
   *
   * Idempotent : skip si player déjà imprisoned OU déjà pending (évite
   * trigger répété quand HP reste à 0 après plusieurs ticks GIGN).
   */
  static async onTerritoryDestroyed(targetPlayerId: string): Promise<void> {
    const sentenceDays = await GameSettingsService.get<number>(
      'gign.combat.sentence_days',
      GIGN_DEFAULTS.sentence_days,
    );

    const ph = await phRepo().findOneBy({ player_id: targetPlayerId });

    // Garde-fou idempotence : si déjà imprisoned ou déjà pending, skip
    if (ph?.imprisoned_until && new Date(ph.imprisoned_until) > new Date()) {
      return;
    }
    if (ph?.pending_imprisonment_at && new Date(ph.pending_imprisonment_at) > new Date()) {
      return;
    }

    // Vérifier si le player est en hôpital — dans ce cas, l'assignPrison sera
    // déclenché au release hôpital (Étape 2.4 hook). Sinon assign maintenant.
    const isInHospital = !!ph?.hospitalized_until && new Date(ph.hospitalized_until) > new Date();

    if (isInHospital) {
      // Marquer pending : à la sortie de l'hôpital, assignPrison sera déclenché.
      // Phase 8.5 — pour l'instant, on stocke via pending_imprisonment_at +
      // pending_sentence_days (réutilisation du pattern existant Phase 8.2).
      await phRepo().update(
        { player_id: targetPlayerId },
        {
          pending_imprisonment_at: ph!.hospitalized_until,
          pending_sentence_days: sentenceDays,
        },
      );

      try {
        await notifRepo().save(notifRepo().create({
          player_id: targetPlayerId,
          type: 'system',
          title: 'Territoire détruit — peine en attente',
          message: `Le GIGN a détruit ton territoire. Peine de ${sentenceDays} jours appliquée à ta sortie d'hôpital.`,
        }));
      } catch { /* silent */ }
      return;
    }

    // Pas en hôpital → assignPrison direct
    try {
      const { PrisonAssignmentService } = await import('./prison-assignment.service');
      await PrisonAssignmentService.assignPrison(targetPlayerId, sentenceDays);
    } catch (err) {
      console.error('[GIGN] onTerritoryDestroyed assignPrison failed:', (err as Error).message);
    }

    try {
      await notifRepo().save(notifRepo().create({
        player_id: targetPlayerId,
        type: 'system',
        title: 'Territoire détruit',
        message: `Le GIGN a détruit ton territoire. ${sentenceDays} jours de prison.`,
      }));
    } catch { /* silent */ }

    emitToPlayer(targetPlayerId, 'gign:territory-destroyed', { sentence_days: sentenceDays });

    // Phase 8.5d (2026-04-29) — Bug 8 fix : deactivate les unités GIGN après
    // la destruction du territoire (mission accomplie côté GIGN). Les units
    // se replient ; cooldown 48h respawn pour ce player target.
    try {
      await PoliceGignCombatService.deactivateGignRaidForPlayer(targetPlayerId);
    } catch (err) {
      console.error('[GIGN] deactivate units after territory destroyed failed:', (err as Error).message);
    }
  }

  /**
   * Phase 8.5d (2026-04-29) — Deactivate toutes les unités GIGN qui ciblent
   * ce player. Setté quand le territoire est détruit (mission accomplie GIGN)
   * OU quand toutes les unités GIGN sont éliminées (cf checkAllUnitsKilled).
   *
   * Effets :
   *   - is_active=false sur les unités GIGN du raid
   *   - last_gign_killed_at = now (cooldown 48h respawn)
   *
   * NB : on n'utilise pas le terme "killed" ici (les units ne sont pas mortes,
   * elles se replient après mission). Mais on réutilise le même cooldown
   * pour cohérence (player ne peut pas avoir un nouveau raid avant 48h).
   */
  static async deactivateGignRaidForPlayer(targetPlayerId: string): Promise<void> {
    await unitRepo()
      .createQueryBuilder()
      .update()
      .set({ is_active: false, status: 'idle' as any })
      .where('type IN (:...types)', { types: ['gign_truck', 'gign_helicopter'] })
      .andWhere('is_active = true')
      .execute();

    await phRepo().update(
      { player_id: targetPlayerId },
      { last_gign_killed_at: new Date() },
    );
  }

  /**
   * Vérifie si le respawn GIGN est en cooldown pour ce player target.
   * Returns true si on doit SKIP le respawn (cooldown actif < 24h).
   */
  static async isRespawnCooldownActive(targetPlayerId: string): Promise<boolean> {
    const ph = await phRepo().findOneBy({ player_id: targetPlayerId });
    if (!ph?.last_gign_killed_at) return false;

    const cooldownHours = await GameSettingsService.get<number>(
      'gign.combat.respawn_cooldown_hours',
      GIGN_DEFAULTS.respawn_cooldown_hours,
    );
    const elapsed = (Date.now() - new Date(ph.last_gign_killed_at).getTime()) / 3600000;
    return elapsed < cooldownHours;
  }
}
