import { AppDataSource } from '../config/database';
import { CartelRecruitPool } from '../models/CartelRecruitPool';
import type { NpcRecruitSlot } from '../models/NpcRecruitPool';
import { CartelGangster } from '../models/CartelGangster';
import { Cartel } from '../models/Cartel';
import { CartelMember } from '../models/CartelMember';
import { Player } from '../models/Player';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerHealth } from '../models/PlayerHealth';
import { GameSetting } from '../models/GameSetting';
import {
  ARCHETYPE_TEMPLATES, NpcArchetype, ArchetypeTemplate,
  ELITE_MIN_CRIMINAL_TIER, ELITE_MIN_RESPECT, ELITE_SPAWN_COOLDOWN_MS,
  generateNpcName, randRange, weightedPick,
} from '../constants/npc-archetypes';
import { v4 as uuid } from 'uuid';

/**
 * Phase 15 Iteration 6.1 (19-04-2026) — Cartel NPC Recruit Service.
 *
 * Mirror de NpcRecruitService mais pour le cartel : pool keyed sur cartel_id.
 * Refresh quotidien à minuit Paris. Recrute un NPC Player + CartelGangster.
 *
 * Limite : 99 gangsters cartel maximum (consigne Q-D utilisateur).
 * Archetypes débloqués selon XP du cartel (pas du joueur).
 * Paiement : depuis treasury_shadow du cartel (même système que gangs).
 */

const poolRepo = () => AppDataSource.getRepository(CartelRecruitPool);
const gangsterRepo = () => AppDataSource.getRepository(CartelGangster);
const cartelRepo = () => AppDataSource.getRepository(Cartel);
const memberRepo = () => AppDataSource.getRepository(CartelMember);
const playerRepo = () => AppDataSource.getRepository(Player);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);

export const CARTEL_GANGSTER_MAX = 99;

export class CartelNpcRecruitService {

  /**
   * Paliers XP cartel → archetypes débloqués (mêmes paliers que joueur).
   */
  private static getEligibleArchetypes(cartelXp: number, allowElite: boolean): NpcArchetype[] {
    const xp = cartelXp ?? 0;
    const archs: NpcArchetype[] = ['street'];
    if (xp >= 10000) archs.push('soldier');
    if (xp >= 20000) archs.push('specialist');
    if (xp >= 30000) archs.push('veteran');
    if (xp >= 40000 && allowElite) archs.push('elite');
    return archs;
  }

  /**
   * Tire la taille du pool dans [0, 1, 2, 3] uniformément (25% chacun)
   * AVEC garde-fou anti-2-zéros : si le pool précédent était vide,
   * on force ≥1 (mirror NpcRecruitService Phase 17 2026-05-04).
   */
  private static rollPoolSize(previousSize: number): number {
    const candidates = previousSize === 0 ? [1, 2, 3] : [0, 1, 2, 3];
    return candidates[Math.floor(Math.random() * candidates.length)];
  }

  /**
   * Refresh le pool d'un cartel.
   * - Mode replace (cron daily, append=false par défaut) : remplace les
   *   slots non recrutés par un nouveau tirage [0,1,2,3].
   * - Mode append (mission Recruter) : ajoute les nouveaux slots aux
   *   non-recrutés existants. forcedSize permet d'imposer la taille.
   */
  static async refreshPoolForCartel(
    cartelId: string,
    allowElite: boolean = false,
    options: { append?: boolean; forcedSize?: number } = {},
  ): Promise<CartelRecruitPool> {
    const existing = await poolRepo().findOne({ where: { cartel_id: cartelId } });
    const previousSize = existing?.slots.filter(s => !s.recruited).length ?? 0;
    const size = options.forcedSize ?? CartelNpcRecruitService.rollPoolSize(previousSize);

    const cartel = await cartelRepo().findOne({ where: { id: cartelId } });
    const cartelXp = cartel?.xp ?? 0;
    const eligibleArchs = CartelNpcRecruitService.getEligibleArchetypes(cartelXp, allowElite);

    const newSlots: NpcRecruitSlot[] = [];
    for (let i = 0; i < size; i++) {
      const eligibleTemplates = ARCHETYPE_TEMPLATES.filter(t => eligibleArchs.includes(t.archetype));
      if (eligibleTemplates.length === 0) break;
      const template = weightedPick(eligibleTemplates);
      newSlots.push(CartelNpcRecruitService.generateSlot(template));
    }

    const slots: NpcRecruitSlot[] = options.append
      ? [...(existing?.slots.filter(s => !s.recruited) ?? []), ...newSlots]
      : newSlots;

    const nextMidnight = CartelNpcRecruitService.getNextMidnightParis();

    let pool = existing ?? null;
    if (pool) {
      pool.size = slots.length;
      pool.has_elite = pool.has_elite || allowElite;
      pool.slots = slots;
      pool.refreshed_at = new Date();
      pool.next_refresh_at = nextMidnight;
    } else {
      pool = poolRepo().create({
        cartel_id: cartelId,
        size: slots.length,
        has_elite: allowElite,
        slots,
        refreshed_at: new Date(),
        next_refresh_at: nextMidnight,
      });
    }

    return poolRepo().save(pool);
  }

  /**
   * CRON daily (midnight Paris) : refresh tous les pools de cartels actifs.
   * Elite alloué à UN seul cartel éligible (tier admin >= 3, respect >= 60).
   */
  static async refreshAllPools(): Promise<{ refreshed: number; eliteAllocated: boolean }> {
    const cartels = await cartelRepo().find({ where: { is_active: true } });
    if (cartels.length === 0) return { refreshed: 0, eliteAllocated: false };

    // Détermine si elite peut spawn (partagé avec le cron joueur via GameSetting)
    let eliteEligibleCartelId: string | null = null;
    const eliteSetting = await AppDataSource.getRepository(GameSetting)
      .findOne({ where: { key: 'cartel_elite_last_spawn_at' } });
    const lastSpawnStr = eliteSetting?.value ? JSON.parse(eliteSetting.value) : '';
    const lastSpawnMs = lastSpawnStr ? new Date(lastSpawnStr).getTime() : 0;
    const eliteReady = Date.now() - lastSpawnMs >= ELITE_SPAWN_COOLDOWN_MS;

    if (eliteReady) {
      for (const c of cartels) {
        // Prend le premier admin humain du cartel pour mesurer l'éligibilité
        const admin = await memberRepo().findOne({ where: { cartel_id: c.id, is_admin: true } });
        if (!admin?.primary_player_id) continue;
        const player = await playerRepo().findOne({ where: { id: admin.primary_player_id } });
        const gauges = await gaugesRepo().findOne({ where: { player_id: admin.primary_player_id } });
        if (
          player &&
          !player.is_npc &&
          player.criminal_tier >= ELITE_MIN_CRIMINAL_TIER &&
          Number(gauges?.respect ?? 0) >= ELITE_MIN_RESPECT
        ) {
          eliteEligibleCartelId = c.id;
          break;
        }
      }
    }

    let refreshed = 0;
    for (const c of cartels) {
      await CartelNpcRecruitService.refreshPoolForCartel(c.id, c.id === eliteEligibleCartelId);
      refreshed++;
    }

    if (eliteEligibleCartelId) {
      const existing = await AppDataSource.getRepository(GameSetting)
        .findOne({ where: { key: 'cartel_elite_last_spawn_at' } });
      if (existing) {
        await AppDataSource.getRepository(GameSetting)
          .update({ key: 'cartel_elite_last_spawn_at' }, { value: JSON.stringify(new Date().toISOString()) });
      } else {
        await AppDataSource.getRepository(GameSetting).save({
          key: 'cartel_elite_last_spawn_at',
          value: JSON.stringify(new Date().toISOString()),
        } as any);
      }
    }

    return { refreshed, eliteAllocated: !!eliteEligibleCartelId };
  }

  /**
   * Recrute un candidat depuis le pool cartel.
   *
   * Vérifie :
   *  - Admin du cartel (sinon: refus)
   *  - Slot existe et non recruté
   *  - Treasury shadow cartel >= cost
   *  - Compte gangsters < CARTEL_GANGSTER_MAX (99)
   *
   * Crée un Player NPC + CartelGangster + débite treasury_shadow.
   */
  static async recruitFromPool(
    cartelId: string,
    playerId: string,
    slotId: string,
  ): Promise<{ success: boolean; message: string; gangster?: any }> {
    // Vérif admin
    const admin = await memberRepo().findOne({
      where: { cartel_id: cartelId, primary_player_id: playerId, is_admin: true },
    });
    if (!admin) {
      // Fallback : officer peut aussi recruter
      const officer = await memberRepo().findOne({
        where: { cartel_id: cartelId, primary_player_id: playerId, is_officer: true },
      });
      if (!officer) return { success: false, message: 'Seuls les admins/officiers du cartel peuvent recruter' };
    }

    const pool = await poolRepo().findOne({ where: { cartel_id: cartelId } });
    if (!pool) return { success: false, message: 'Pas de pool de recrues actif pour ce cartel' };

    const slotIdx = pool.slots.findIndex(s => s.slot_id === slotId);
    if (slotIdx === -1) return { success: false, message: 'Candidat introuvable dans le pool' };

    const slot = pool.slots[slotIdx];
    if (slot.recruited) return { success: false, message: 'Ce candidat a déjà été recruté' };

    // Compte actuel
    const currentCount = await gangsterRepo().count({ where: { cartel_id: cartelId } });
    if (currentCount >= CARTEL_GANGSTER_MAX) {
      return { success: false, message: `Limite atteinte (${CARTEL_GANGSTER_MAX} gangsters cartel max)` };
    }

    // Trésorerie cartel
    const cartel = await cartelRepo().findOne({ where: { id: cartelId } });
    if (!cartel) return { success: false, message: 'Cartel introuvable' };
    if ((cartel.treasury_shadow ?? 0) < slot.cost) {
      return {
        success: false,
        message: `Trésorerie ombre insuffisante. Coût: ${slot.cost} ∞ (trésor: ${cartel.treasury_shadow ?? 0})`,
      };
    }

    // Débit treasury
    cartel.treasury_shadow = (cartel.treasury_shadow ?? 0) - slot.cost;
    await cartelRepo().save(cartel);

    // Create NPC player
    const npcPlayer = playerRepo().create({
      username: slot.name.replace(/\s+/g, '_') + '_c' + uuid().slice(0, 4),
      email: `npc_cartel_${uuid().slice(0, 8)}@mafiaz.world`,
      password_hash: null,
      oauth_provider: 'email',
      is_npc: true,
      npc_role: 'gangster',
      is_active: true,
      onboarding_completed: true,
      current_lat: null,
      current_lon: null,
      start_lat: null,
      start_lon: null,
    } as any);
    const savedNpc = await playerRepo().save(npcPlayer as any) as unknown as Player;
    await gaugesRepo().save(gaugesRepo().create({ player_id: savedNpc.id }));
    await balancesRepo().save(balancesRepo().create({ player_id: savedNpc.id }));
    await healthRepo().save(healthRepo().create({ player_id: savedNpc.id }));

    // Create CartelGangster
    const gangster = gangsterRepo().create({
      cartel_id: cartelId,
      player_id: savedNpc.id,
      role: 'member',
      grade: slot.grade,
      hit_points: slot.hit_points,
      loyalty: slot.loyalty,
      experience: slot.grade * 1000,
      influence_radius_m: 300,
      specialized_position: slot.specialty ?? null,
    });
    await gangsterRepo().save(gangster);

    // Mark slot recruited
    pool.slots[slotIdx].recruited = true;
    await poolRepo().save(pool);

    return {
      success: true,
      message: `${slot.name} recruté pour le cartel (${slot.cost} ∞-ombre)`,
      gangster: { player_id: savedNpc.id, grade: slot.grade, loyalty: slot.loyalty },
    };
  }

  /** Écarte un candidat sans le recruter (bouton X). */
  static async dismissCandidate(cartelId: string, slotId: string): Promise<{ success: boolean; message: string }> {
    const pool = await poolRepo().findOne({ where: { cartel_id: cartelId } });
    if (!pool) return { success: false, message: 'Pas de pool actif' };
    const slotIdx = pool.slots.findIndex(s => s.slot_id === slotId);
    if (slotIdx === -1) return { success: false, message: 'Candidat introuvable' };
    pool.slots[slotIdx].recruited = true;
    await poolRepo().save(pool);
    return { success: true, message: 'Candidat écarté' };
  }

  /** Retourne le pool actuel du cartel (pour API). */
  static async getPool(cartelId: string): Promise<CartelRecruitPool | null> {
    return poolRepo().findOne({ where: { cartel_id: cartelId } });
  }

  /** Liste des gangsters du cartel (avec infos player). */
  static async listGangsters(cartelId: string): Promise<any[]> {
    const gangsters = await gangsterRepo().find({ where: { cartel_id: cartelId } });
    const result: any[] = [];
    for (const g of gangsters) {
      const p = await playerRepo().findOne({ where: { id: g.player_id } });
      result.push({
        cartel_id: g.cartel_id,
        player_id: g.player_id,
        role: g.role,
        grade: g.grade,
        experience: g.experience,
        hit_points: g.hit_points,
        loyalty: g.loyalty,
        daily_salary: g.daily_salary,
        total_paid: g.total_paid,
        last_paid_at: g.last_paid_at,
        unpaid_since: g.unpaid_since,
        last_mission_at: g.last_mission_at,
        specialized_position: g.specialized_position,
        assigned_vehicle_id: g.assigned_vehicle_id,
        assigned_weapon: g.assigned_weapon,
        hospitalized_until: g.hospitalized_until,
        player: p ? { username: p.username, character_name: p.character_name } : null,
      });
    }
    return result;
  }

  /** Vire un gangster du cartel (DELETE row + player NPC). */
  static async removeGangster(cartelId: string, playerId: string, removerPlayerId: string): Promise<{ success: boolean; message: string }> {
    // Vérif admin
    const admin = await memberRepo().findOne({
      where: { cartel_id: cartelId, primary_player_id: removerPlayerId, is_admin: true },
    });
    if (!admin) {
      const officer = await memberRepo().findOne({
        where: { cartel_id: cartelId, primary_player_id: removerPlayerId, is_officer: true },
      });
      if (!officer) return { success: false, message: 'Seuls admins/officiers peuvent virer' };
    }

    const g = await gangsterRepo().findOne({ where: { cartel_id: cartelId, player_id: playerId } });
    if (!g) return { success: false, message: 'Gangster introuvable dans ce cartel' };

    // Heat +1 si loyalty < 50 (miroir GangService.removeMember)
    if (g.loyalty < 50) {
      const c = await cartelRepo().findOne({ where: { id: cartelId } });
      if (c) {
        c.heat_current = Number(c.heat_current ?? 0) + 1;
        await cartelRepo().save(c);
      }
    }

    await gangsterRepo().delete({ cartel_id: cartelId, player_id: playerId });
    // Le Player NPC reste en DB pour audit (historique missions)
    return { success: true, message: 'Gangster viré du cartel' };
  }

  // ─── Private helpers ───────────────────────────────────────────────

  private static generateSlot(template: ArchetypeTemplate): NpcRecruitSlot {
    const specialty = template.specialties[Math.floor(Math.random() * template.specialties.length)];
    return {
      slot_id: uuid(),
      archetype: template.archetype,
      name: generateNpcName(),
      grade: randRange(template.grade[0], template.grade[1]),
      hit_points: randRange(template.hit_points[0], template.hit_points[1]),
      loyalty: randRange(template.loyalty[0], template.loyalty[1]),
      cost: Math.round(randRange(template.cost[0], template.cost[1]) / 100) * 100,
      specialty,
      description: template.description_template,
      recruited: false,
    };
  }

  private static getNextMidnightParis(): Date {
    const now = new Date();
    const month = now.getUTCMonth();
    const offsetH = (month >= 2 && month <= 9) ? 2 : 1;
    const parisHour = (now.getUTCHours() + offsetH) % 24;
    const hoursUntilMidnight = parisHour === 0 ? 24 : 24 - parisHour;
    return new Date(now.getTime() + hoursUntilMidnight * 60 * 60 * 1000);
  }
}
