import type { POICategory } from '../models/POI';

/**
 * 4 super-catégories top-level de POI (Phase 2, 2026-04-20).
 *
 * Règle : classification fonctionnelle — ce que le joueur PEUT FAIRE au POI :
 *   - commercial  : commerces lambda sans action spéciale (bar, restaurant, shop, garage…)
 *   - residentiel : toutes résidences + planques
 *   - special     : POIs avec actions UI custom (banque, casino, concessionnaire, armurerie,
 *                   caviste, coiffeur, carrosserie, associations, docks, bijouterie, mode…)
 *   - service     : infrastructures publiques (hôpital, commissariat, mairie, tribunal,
 *                   poste, change, bibliothèque, lieu de culte, pharmacie, prison, clinique)
 *
 * La LÉGALITÉ (is_legal, illegal_activity_type) est un AXE ORTHOGONAL — un business avec
 * activité illégale cachée garde sa super-catégorie publique ('commercial' ou 'special')
 * mais est marqué via un badge `has_illegal` quand l'info est révélée.
 */
export type POISuperCategory = 'commercial' | 'residentiel' | 'special' | 'service';

export const POI_SUPER_CATEGORIES: POISuperCategory[] = [
  'commercial', 'residentiel', 'special', 'service',
];

export const POI_SUPER_CATEGORY_LABELS: Record<POISuperCategory, string> = {
  commercial:   'Commercial',
  residentiel:  'Résidentiel',
  special:      'Spécial',
  service:      'Service',
};

/**
 * Business types qui sont des COMMERCES SPÉCIAUX (actions UI custom).
 * Tous les autres business.type → super-cat 'commercial' par défaut.
 */
const SPECIAL_BUSINESS_TYPES = new Set<string>([
  'armurerie', 'banque_joueur', 'casino', 'carrosserie', 'coiffeur', 'caviste',
  'association_caritative', 'association_ecologique', 'association_sociale',
  'concessionnaire', 'bijouterie', 'fashion', 'fabric', 'opticien',
  'fleurist', 'kiosk_media', 'library_shop', 'shoes', 'mode',
]);

/**
 * Icônes OSM (amenity=*, shop=*) qui identifient un POI SPÉCIAL.
 * Utilisé pour les POIs sans `entity_id` (orphelins) ou avant résolution.
 */
const SPECIAL_ICONS = new Set<string>([
  'bank', 'casino', 'car_rental', 'ferry_terminal', 'kiosk', 'wine',
  'hairdresser', 'jewelry', 'fashion', 'fabric', 'perfumery', 'shoes',
  'optician', 'florist', 'charity', 'second_hand', 'variety_store',
  'car_repair', 'trade', 'houseware',
  'windmill', 'archaeological_site', 'bunker', 'fort',
]);

/**
 * Icônes OSM qui identifient un POI SERVICE (infrastructure publique).
 */
const SERVICE_ICONS = new Set<string>([
  'police', 'taxi', 'hospital', 'clinic', 'pharmacy', 'townhall',
  'courthouse', 'prison', 'post_office', 'bureau_de_change',
  'library', 'place_of_worship',
]);

/**
 * Icônes OSM résidentiel.
 */
const RESIDENTIAL_ICONS = new Set<string>([
  'house', 'apartment', 'apartments', 'bungalow', 'residential',
  'residence', 'studio', 'squat', 'villa', 'manor', 'room', 'chambre',
  'penthouse',
]);

export interface SuperCategoryOptions {
  businessType?: string | null;
  isLegal?: boolean | null;
  illegalActivityType?: string | null;
  isPlanqueActive?: boolean | null;
}

/**
 * Dérive la super-catégorie d'un POI depuis sa POICategory + attributs entité.
 *
 * Priorité :
 *   1. businessType ∈ SPECIAL_BUSINESS_TYPES → 'special'
 *   2. POICategory business_*                → 'commercial' (ou 'special' via spec)
 *   3. POICategory residence                 → 'residentiel'
 *   4. POICategory warehouse_*               → 'special' (entrepôt = action stockage)
 *   5. POICategory infrastructure_*          → 'service'
 *   6. POICategory blackmarket / threat      → 'special'
 *   7. Fallback legacy null → 'commercial'
 */
export function toSuperCategory(
  category: POICategory | null | undefined,
  options: SuperCategoryOptions = {},
): POISuperCategory {
  const bt = (options.businessType || '').toLowerCase();
  if (bt && SPECIAL_BUSINESS_TYPES.has(bt)) return 'special';

  switch (category) {
    case 'business_food':
    case 'business_retail':
    case 'business_service':
    case 'business_production':
    case 'business_nightlife':
      return 'commercial';

    case 'business_finance':
    case 'business_weapons':
      return 'special';

    case 'residence':
      return 'residentiel';

    case 'warehouse_storage':
    case 'warehouse_drug_lab':
    case 'warehouse_weapons_cache':
    case 'warehouse_safe_house':
      return 'special';

    case 'infrastructure_police':
    case 'infrastructure_town_hall':
    case 'infrastructure_courthouse':
    case 'infrastructure_hospital':
    case 'infrastructure_pharmacy':
    case 'infrastructure_bank':
    case 'infrastructure_post_office':
    case 'infrastructure_religious':
    case 'infrastructure_exchange':
      // Banque = spécial (blanchiment), le reste = service public
      return category === 'infrastructure_bank' ? 'special' : 'service';

    case 'blackmarket':
    case 'threat':
      return 'special';

    case 'other':
    case null:
    case undefined:
    default:
      return 'commercial';
  }
}

/**
 * Dérive la super-catégorie depuis l'icône OSM seule (cas orphans, entity_id=null).
 */
export function superCategoryFromIcon(icon: string | null | undefined): POISuperCategory | null {
  if (!icon) return null;
  const ic = icon.toLowerCase();
  if (SPECIAL_ICONS.has(ic)) return 'special';
  if (SERVICE_ICONS.has(ic)) return 'service';
  if (RESIDENTIAL_ICONS.has(ic)) return 'residentiel';
  // Tout le reste (bar, restaurant, nightclub, shop, supermarket, bakery, convenience,
  // food_court, biergarten, garage, tabac, boulangerie, etc.) → commercial
  return 'commercial';
}

/**
 * Résout la super-catégorie ET le badge `has_illegal` (activité illégale révélée).
 * À utiliser côté backend pour exposer au frontend (POI details + visibility loop).
 */
export function resolvePOICategorization(
  category: POICategory | null | undefined,
  options: SuperCategoryOptions & { illegalRevealed?: boolean } = {},
): { super_category: POISuperCategory; has_illegal: boolean } {
  const superCat = toSuperCategory(category, options);
  // Badge "has_illegal" visible seulement si l'info a été révélée (owner ou reveal)
  const hasIllegal = !!(options.illegalRevealed && options.illegalActivityType);
  return { super_category: superCat, has_illegal: hasIllegal };
}
