<?php
/**
 * DBA GeoBot Registry — Scalable country configuration engine
 *
 * ═══════════════════════════════════════════════════════════════════════
 *  SCALABILITY: Adding a new country = adding ONE config block below.
 *  All other GeoBot classes are 100% country-agnostic.
 *  Current countries: France (active), Italy, Spain, Portugal (stubs).
 * ═══════════════════════════════════════════════════════════════════════
 *
 *  ZERO CONFLICT with core Damalion or PE NewsBot:
 *    - Option keys:   dba_geo_{country}_settings, dba_geo_{country}_last_run
 *    - Meta keys:     _dba_geo_{country}_auto_created, _dba_geo_{country}_commune
 *    - Cron hooks:    dba_geo_{country}_daily_generation
 *    - Transients:    dba_geo_{country}_generation_progress
 *    - History:       dba_geo_{country}_dedupe_history
 *    - Admin page:    dba-geo-{country}
 *
 * @since 2.8.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_GeoBot_Registry {

    /**
     * Master country configurations.
     *
     * To add a new country:
     *   1. Copy any existing block below
     *   2. Change the key and all fields
     *   3. Populate the 'communes' array (or load from CSV/Excel on activation)
     *   4. Done — admin page, scheduler, generator, validator all auto-register.
     *
     * @return array Keyed by country slug.
     */
    public static function get_countries() {

        return array(

            /* ═══════════════════════════════════════════════════════════
             *  🇫🇷 FRANCE — Active
             * ═══════════════════════════════════════════════════════════ */
            'france' => array(
                'key'                => 'france',
                'label'              => '🇫🇷 France Investment Blog',
                'menu_label'         => '🇫🇷 France GeoBot',
                'flag'               => '🇫🇷',
                'language'           => 'fr',
                'wpml_code'          => 'fr',
                'timezone'           => 'Europe/Paris',
                'publish_hour'       => 9,
                'publish_min'        => 0,
                'cron_hour_utc'      => 7,   // 07:00 UTC = 09:00 CET (winter) / 08:00 UTC summer
                'default_posting_days' => array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 3,
                'wp_category'        => 'Investissements',
                'blog_url'           => 'https://www.damalion.com/blog/?lang=fr',
                'post_language_note' => 'ALL POSTS MUST BE IN FRENCH',

                // CTA — from client specification
                'cta_text'       => 'Damalion accompagne les family offices internationaux, les entrepreneurs ainsi que les fonds de private equity et de capital-risque dans l\'identification d\'opportunités leur permettant d\'atteindre leurs objectifs.',
                'cta_link_text'  => 'Contactez dès maintenant vos experts Damalion.',
                'cta_link_url'   => 'https://www.damalion.com/connectons-nous/?lang=fr',

                // Word count
                'word_count_min' => 800,
                'word_count_max' => 1200,

                // H2 section titles (in target language)
                'h2_sections' => array(
                    'Fondamentaux démographiques',
                    'Échelle économique et densité des entreprises',
                    'Principaux secteurs d\'activité',
                    'Présence d\'entreprises',
                    'Développement urbain et projets d\'infrastructure',
                    'Rues et emplacements fréquentés',
                    'Perspective d\'investissement',
                ),

                // H1 format
                'h1_format' => 'Investir en France : focus sur {COMMUNE}',

                // Linking rules
                'link_rules' => array(
                    'commune_link_once'   => true,
                    'region_link_once'    => true,
                    'company_links'       => true,  // every company name must link to official site
                    'no_hr'              => true,
                    'no_strong'          => true,
                    'no_city_link_in_h1' => true,
                ),

                // Slug format
                'slug_format' => 'investir-en-france-focus-sur-{commune_slug}',

                // ═══════════════════════════════════════════════════════════
                //  ARTICLE STRUCTURE TEMPLATE (structural guide — NOT verbatim)
                //  AI uses this as a blueprint for SECTION ORDER and CONTENT TYPE.
                //  Every sentence must be uniquely composed per city.
                // ═══════════════════════════════════════════════════════════
                'article_structure' => array(
                    'intro' => array(
                        'purpose'  => '2-3 paragraphs introducing the city as an investment destination',
                        'must_include' => 'city name (linked once to mairie), region name, investment keyword',
                        'guidance' => 'Describe what makes THIS specific city distinct — its economic identity, geographic role, recent trajectory. Do NOT use generic filler.',
                    ),
                    'sections' => array(
                        array(
                            'h2' => 'Fondamentaux démographiques',
                            'content_type' => 'Population data: city proper + metro area + municipalities count. Growth trend. Age profile. What this means for investors (demand, workforce, housing).',
                            'data_fields' => 'pop_city, metro_name, pop_metro, metro_municipalities',
                        ),
                        array(
                            'h2' => 'Échelle économique et densité des entreprises',
                            'content_type' => 'Company count, job count, new company creation. Economic structure (diversified vs specialized). Resilience to shocks.',
                            'data_fields' => 'company_count, job_count, new_companies',
                        ),
                        array(
                            'h2' => 'Principaux secteurs d\'activité',
                            'content_type' => 'List 4-6 key sectors with brief descriptions of local activity in each. Use research data for sector names.',
                            'data_fields' => 'industry_sectors',
                        ),
                        array(
                            'h2' => 'Présence d\'entreprises',
                            'content_type' => 'Major companies headquartered or with significant presence. Each company name MUST be linked to official site. Mix of large groups and SMEs.',
                            'data_fields' => 'major_companies (name, url, sector)',
                        ),
                        array(
                            'h2' => 'Développement urbain et projets d\'infrastructure',
                            'content_type' => 'Major urban development projects, infrastructure investments, regeneration zones. Link to official project pages when available.',
                            'data_fields' => 'urban_projects (name, url, description, scale)',
                        ),
                        array(
                            'h2' => 'Rues et emplacements fréquentés',
                            'content_type' => 'Prime commercial streets, business districts, high-footfall areas. What makes them attractive for retail/office investment.',
                            'data_fields' => 'prime_streets',
                        ),
                        array(
                            'h2' => 'Perspective d\'investissement',
                            'content_type' => 'Synthesis: why this city matters for investors. Position vs other French cities. Risk/reward profile. Forward-looking without speculation.',
                            'data_fields' => 'synthesis of all above',
                        ),
                    ),
                ),

                // ═══════════════════════════════════════════════════════════
                //  BANNED PHRASES — Template sentences that MUST NEVER appear.
                //  Validator Gate 8 checks for these. AI is also instructed to avoid them.
                //  These are extracted from the original template to prevent copy-paste.
                // ═══════════════════════════════════════════════════════════
                'banned_phrases' => array(
                    'often cited among',
                    'has moved well beyond its historical role',
                    'consolidated its position as a diversified economic hub',
                    'for investors looking beyond Paris',
                    'combination of demographic momentum',
                    'continues to reshape both its economic base',
                    'population growth has remained structurally positive',
                    'driven by employment opportunities, higher education, and internal migration',
                    'the demographic profile is comparatively young',
                    'with a large share of residents under 40',
                    'supports workforce renewal, household formation',
                    'reduce long-term demand risk and provide visibility',
                    'residential, retail, and service-oriented assets',
                    'one of the leading economic zones',
                    'reflecting entrepreneurial depth',
                    'continuous renewal of the local economic fabric',
                    'the economy is not dependent on a single driver',
                    'developed a balanced structure combining',
                    'absorb economic shocks while maintaining steady growth',
                    'anchors high-value industrial employment',
                    'the local corporate landscape combines',
                    'creates multiple entry points for private equity strategies',
                    'minority growth investments to platform build-ups',
                    'asset-backed operating companies',
                    'urban transformation has become a central pillar',
                    'economic and social activity concentrates around',
                    'well-defined corridors and nodes',
                    'stronger liquidity, rental stability, and resilience across cycles',
                    'occupies a distinct position among French regional cities',
                    'without the pricing pressure seen in Paris',
                    'long-term fundamentals rather than short-term momentum',
                    'capital reallocation toward resilient regional hubs',
                    'less an alternative and increasingly a reference point',
                    'over the past decade',
                    'for more than a decade',
                    'has become less an alternative',
                ),

                // Research instructions for the AI
                'research_instructions' => 'You are a financial research assistant specializing in French cities and investment opportunities. Search for real, current data about the given commune. Focus on: official city hall URL (mairie), intercommunality/métropole/EPCI, major local companies with official domains, urban development projects, key commercial streets. Return factual, verifiable data only.',

                // Communes loaded from option (populated on activation from Excel)
                'communes_option_key' => 'dba_geo_france_communes',

                // Option / meta / cron key patterns (auto-computed from 'key')
                'option_prefix'     => 'dba_geo_france_',
                'meta_prefix'       => '_dba_geo_france_',
                'cron_hook'         => 'dba_geo_france_daily_generation',
                'progress_transient'=> 'dba_geo_france_generation_progress',
                'history_option'    => 'dba_geo_france_dedupe_history',
                'settings_option'   => 'dba_geo_france_settings',
                'last_run_option'   => 'dba_geo_france_last_run',
                'admin_slug'        => 'dba-geo-france',
            ),

            /* ═══════════════════════════════════════════════════════════
             *  🇮🇹 ITALY — Full Italian-language config (v2.13.0)
             *
             *  EVERY prompt-facing field is in Italian so the AI
             *  writes content in Italian, NOT English.
             * ═══════════════════════════════════════════════════════════ */
            'italy' => array(
                'key'                => 'italy',
                'label'              => '🇮🇹 Italia Investment Blog',
                'menu_label'         => '🇮🇹 Italia GeoBot',
                'flag'               => '🇮🇹',
                'language'           => 'it',
                'wpml_code'          => 'it',
                'timezone'           => 'Europe/Rome',
                'publish_hour'       => 9,
                'publish_min'        => 0,
                'cron_hour_utc'      => 7,
                'default_posting_days' => array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 3,
                'wp_category'            => 'Investimenti',
                'wp_category_translated' => 'Investire in Italia',
                'blog_url'           => 'https://www.damalion.com/blog/?lang=it',

                // ── LANGUAGE DIRECTIVE — read by system prompt builder ──
                'post_language_note' => 'Questo articolo DEVE essere scritto INTERAMENTE in italiano. Ogni titolo, ogni paragrafo, ogni frase, ogni intestazione H2, ogni meta description — TUTTO in lingua italiana. NON scrivere in inglese. Se l\'articolo contiene testo in inglese verrà RIFIUTATO.',

                // ── CTA — Italian ──
                'cta_text'       => 'Damalion accompagna investitori, imprenditori e family office nella strutturazione e nella conformità delle loro operazioni in Italia.',
                'cta_link_text'  => 'Contatta ora i tuoi esperti Damalion.',
                'cta_link_url'   => 'https://www.damalion.com/lets-connect/?lang=it',

                // ── Word count ──
                'word_count_min' => 800,
                'word_count_max' => 1200,

                // ── H1 format (Italian) ──
                'h1_format' => 'Investire in Italia: focus su {COMMUNE}',

                // ── Slug format (Italian) ──
                'slug_format' => 'investire-in-italia-focus-su-{commune_slug}',

                // ── Linking rules ──
                'link_rules' => array(
                    'commune_link_once'   => true,
                    'region_link_once'    => true,
                    'company_links'       => true,
                    'no_hr'              => true,
                    'no_strong'          => true,
                    'no_city_link_in_h1' => true,
                ),

                // ── H2 section titles — ALL ITALIAN ──
                'h2_sections' => array(
                    'Fondamentali demografici',
                    'Scala economica e densità delle imprese',
                    'Principali settori industriali',
                    'Presenza aziendale',
                    'Sviluppo urbano e progetti infrastrutturali',
                    'Strade e luoghi frequentati',
                    'Prospettiva di investimento',
                ),

                // ═══════════════════════════════════════════════════════════
                //  ARTICLE STRUCTURE — ALL ITALIAN
                //  This is what the AI reads to know WHAT to write and HOW.
                //  If this is in English, the AI writes in English.
                // ═══════════════════════════════════════════════════════════
                'article_structure' => array(
                    'intro' => array(
                        'purpose'      => '2-3 paragrafi che presentano la città come destinazione di investimento',
                        'must_include' => 'Nome della città (con link al sito del comune), nome della regione, parola chiave investimento',
                        'guidance'     => 'Descrivere ciò che rende QUESTA città specifica e distinta — la sua identità economica, il suo ruolo geografico, la sua traiettoria recente. NON usare frasi generiche. Scrivere TUTTO in italiano.',
                    ),
                    'sections' => array(
                        array(
                            'h2'           => 'Fondamentali demografici',
                            'content_type' => 'Dati sulla popolazione: città + area metropolitana + numero comuni. Tendenza di crescita. Profilo per età. Cosa significa per gli investitori (domanda, forza lavoro, alloggi).',
                            'data_fields'  => 'pop_city, metro_name, pop_metro, metro_municipalities',
                        ),
                        array(
                            'h2'           => 'Scala economica e densità delle imprese',
                            'content_type' => 'Numero di imprese, posti di lavoro, creazione di nuove imprese. Struttura economica (diversificata o specializzata). Resilienza agli shock.',
                            'data_fields'  => 'company_count, job_count, new_companies',
                        ),
                        array(
                            'h2'           => 'Principali settori industriali',
                            'content_type' => 'Elenco di 4-6 settori chiave con brevi descrizioni dell\'attività locale in ciascuno. Usare i dati della ricerca per i nomi dei settori.',
                            'data_fields'  => 'industry_sectors',
                        ),
                        array(
                            'h2'           => 'Presenza aziendale',
                            'content_type' => 'Principali aziende con sede o presenza significativa. Ogni nome di azienda DEVE essere collegato al sito ufficiale. Mix di grandi gruppi e PMI.',
                            'data_fields'  => 'major_companies (nome, url, settore)',
                        ),
                        array(
                            'h2'           => 'Sviluppo urbano e progetti infrastrutturali',
                            'content_type' => 'Grandi progetti di sviluppo urbano, investimenti infrastrutturali, zone di riqualificazione. Collegare alle pagine ufficiali dei progetti quando disponibili.',
                            'data_fields'  => 'urban_projects (nome, url, descrizione, scala)',
                        ),
                        array(
                            'h2'           => 'Strade e luoghi frequentati',
                            'content_type' => 'Strade commerciali principali, distretti business, aree ad alto traffico. Cosa le rende attraenti per investimenti retail/uffici.',
                            'data_fields'  => 'prime_streets',
                        ),
                        array(
                            'h2'           => 'Prospettiva di investimento',
                            'content_type' => 'Sintesi: perché questa città è importante per gli investitori. Posizionamento rispetto ad altre città italiane. Profilo rischio/rendimento. Prospettiva futura senza speculazioni.',
                            'data_fields'  => 'sintesi di tutti i dati precedenti',
                        ),
                    ),
                ),

                // ═══════════════════════════════════════════════════════════
                //  BANNED PHRASES — English + Italian generics
                //  Gate 8 rejects any article containing these.
                // ═══════════════════════════════════════════════════════════
                'banned_phrases' => array(
                    // English — must NEVER appear in Italian articles
                    'whether you are',
                    'this city offers',
                    'a dynamic city',
                    'a vibrant city',
                    'a thriving city',
                    'ideal destination for investors',
                    'strategic location',
                    'rich history',
                    'diverse economy',
                    'growing economy',
                    'business-friendly',
                    'investment opportunities abound',
                    'hub for innovation',
                    'gateway to',
                    'at the crossroads',
                    'in conclusion',
                    'in summary',
                    'it is worth noting',
                    'it should be noted',
                    'last but not least',
                    'without a doubt',
                    'needless to say',
                    'has moved well beyond its historical role',
                    'for investors looking beyond',
                    'combination of demographic momentum',
                    'population growth has remained structurally positive',
                    'the demographic profile is comparatively young',
                    'reflecting entrepreneurial depth',
                    'continuous renewal of the local economic fabric',
                    'the economy is not dependent on a single driver',
                    'absorb economic shocks while maintaining steady growth',
                    'creates multiple entry points for private equity strategies',
                    'urban transformation has become a central pillar',
                    'well-defined corridors and nodes',
                    'long-term fundamentals rather than short-term momentum',
                    'less an alternative and increasingly a reference point',
                    'over the past decade',
                    // Italian generics — lazy template filler
                    'che tu sia',
                    'questa città offre',
                    'una città dinamica',
                    'una città vivace',
                    'una città fiorente',
                    'destinazione ideale per gli investitori',
                    'posizione strategica',
                    'ricca storia',
                    'economia diversificata',
                    'economia in crescita',
                    'favorevole agli affari',
                    'le opportunità di investimento abbondano',
                    'polo di innovazione',
                    'porta d\'accesso a',
                    'al crocevia',
                    'in conclusione',
                    'in sintesi',
                    'per riassumere',
                    'nel complesso',
                    'vale la pena notare',
                    'va sottolineato',
                    'ultimo ma non meno importante',
                    'senza ombra di dubbio',
                    'inutile dire che',
                    'nell\'ultimo decennio',
                ),

                // ── Research instructions — ITALIAN output required ──
                'research_instructions' => 'Sei un assistente di ricerca finanziaria specializzato nelle città italiane e nelle opportunità di investimento. Cerca dati reali e attuali sul comune indicato. Concentrati su: URL ufficiale del comune, area metropolitana, principali aziende locali con domini ufficiali, progetti di sviluppo urbano, strade commerciali principali. Restituisci SOLO dati fattuali e verificabili. Tutti i nomi di settori, descrizioni di progetti e testi devono essere in ITALIANO.',

                // ── Technical keys (DO NOT CHANGE) ──
                'communes_option_key' => 'dba_geo_italy_communes',
                'option_prefix'     => 'dba_geo_italy_',
                'meta_prefix'       => '_dba_geo_italy_',
                'cron_hook'         => 'dba_geo_italy_daily_generation',
                'progress_transient'=> 'dba_geo_italy_generation_progress',
                'history_option'    => 'dba_geo_italy_dedupe_history',
                'settings_option'   => 'dba_geo_italy_settings',
                'last_run_option'   => 'dba_geo_italy_last_run',
                'admin_slug'        => 'dba-geo-italy',
            ),

            /* ═══════════════════════════════════════════════════════════
             *  🇪🇸 SPAIN — Stub (ready to activate)
             * ═══════════════════════════════════════════════════════════ */
            'spain' => array(
                'key'                => 'spain',
                'label'              => '🇪🇸 Spain Investment Blog',
                'menu_label'         => '🇪🇸 Spain GeoBot',
                'flag'               => '🇪🇸',
                'language'           => 'es',
                'wpml_code'          => 'es',
                'timezone'           => 'Europe/Madrid',
                'publish_hour'       => 9,
                'publish_min'        => 0,
                'cron_hour_utc'      => 7,
                'default_posting_days' => array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 3,
                'wp_category'        => 'Inversiones',
                'blog_url'           => 'https://www.damalion.com/blog/?lang=es',
                'post_language_note' => 'ALL POSTS MUST BE IN SPANISH',

                'cta_text'       => 'Damalion acompaña a family offices internacionales, emprendedores y fondos de private equity y capital riesgo en la identificación de oportunidades para alcanzar sus objetivos.',
                'cta_link_text'  => 'Contacte ahora con sus expertos Damalion.',
                'cta_link_url'   => 'https://www.damalion.com/connectons-nous/?lang=es',

                'word_count_min' => 800,
                'word_count_max' => 1200,

                'h2_sections' => array(
                    'Fundamentos demográficos',
                    'Escala económica y densidad empresarial',
                    'Principales sectores industriales',
                    'Presencia corporativa',
                    'Desarrollo urbano y proyectos de infraestructura',
                    'Calles y ubicaciones frecuentadas',
                    'Perspectiva de inversión',
                ),

                'h1_format' => 'Invertir en España: enfoque en {COMMUNE}',
                'link_rules' => array(
                    'commune_link_once' => true, 'region_link_once' => true,
                    'company_links' => true, 'no_hr' => true, 'no_strong' => true,
                    'no_city_link_in_h1' => true,
                ),
                'slug_format' => 'invertir-en-espana-enfoque-en-{commune_slug}',
                'research_instructions' => 'You are a financial research assistant specializing in Spanish cities and investment opportunities. Search for real, current data about the given municipality. Focus on: official city hall URL (ayuntamiento), metropolitan area, major local companies with official domains, urban development projects, key commercial streets. Return factual, verifiable data only.',
                'communes_option_key' => 'dba_geo_spain_communes',

                'option_prefix'     => 'dba_geo_spain_',
                'meta_prefix'       => '_dba_geo_spain_',
                'cron_hook'         => 'dba_geo_spain_daily_generation',
                'progress_transient'=> 'dba_geo_spain_generation_progress',
                'history_option'    => 'dba_geo_spain_dedupe_history',
                'settings_option'   => 'dba_geo_spain_settings',
                'last_run_option'   => 'dba_geo_spain_last_run',
                'admin_slug'        => 'dba-geo-spain',
            ),

            /* ═══════════════════════════════════════════════════════════
             *  🇵🇹 PORTUGAL — Stub (ready to activate)
             * ═══════════════════════════════════════════════════════════ */
            'portugal' => array(
                'key'                => 'portugal',
                'label'              => '🇵🇹 Portugal Investment Blog',
                'menu_label'         => '🇵🇹 Portugal GeoBot',
                'flag'               => '🇵🇹',
                'language'           => 'pt',
                'wpml_code'          => 'pt-pt',
                'timezone'           => 'Europe/Lisbon',
                'publish_hour'       => 9,
                'publish_min'        => 0,
                'cron_hour_utc'      => 9,   // Lisbon = UTC+0 winter, UTC+1 summer
                'default_posting_days' => array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 3,
                'wp_category'        => 'Investimentos',
                'blog_url'           => 'https://www.damalion.com/blog/?lang=pt-pt',
                'post_language_note' => 'ALL POSTS MUST BE IN PORTUGUESE',

                'cta_text'       => 'A Damalion acompanha family offices internacionais, empreendedores e fundos de private equity e capital de risco na identificação de oportunidades para atingir os seus objetivos.',
                'cta_link_text'  => 'Contacte agora os seus especialistas Damalion.',
                'cta_link_url'   => 'https://www.damalion.com/connectons-nous/?lang=pt-pt',

                'word_count_min' => 800,
                'word_count_max' => 1200,

                'h2_sections' => array(
                    'Fundamentos demográficos',
                    'Escala económica e densidade empresarial',
                    'Principais setores industriais',
                    'Presença empresarial',
                    'Desenvolvimento urbano e projetos de infraestrutura',
                    'Ruas e locais frequentados',
                    'Perspetiva de investimento',
                ),

                'h1_format' => 'Investir em Portugal: foco em {COMMUNE}',
                'link_rules' => array(
                    'commune_link_once' => true, 'region_link_once' => true,
                    'company_links' => true, 'no_hr' => true, 'no_strong' => true,
                    'no_city_link_in_h1' => true,
                ),
                'slug_format' => 'investir-em-portugal-foco-em-{commune_slug}',
                'research_instructions' => 'You are a financial research assistant specializing in Portuguese cities and investment opportunities. Search for real, current data about the given municipality. Focus on: official city hall URL (câmara municipal), metropolitan area, major local companies with official domains, urban development projects, key commercial streets. Return factual, verifiable data only.',
                'communes_option_key' => 'dba_geo_portugal_communes',

                'option_prefix'     => 'dba_geo_portugal_',
                'meta_prefix'       => '_dba_geo_portugal_',
                'cron_hook'         => 'dba_geo_portugal_daily_generation',
                'progress_transient'=> 'dba_geo_portugal_generation_progress',
                'history_option'    => 'dba_geo_portugal_dedupe_history',
                'settings_option'   => 'dba_geo_portugal_settings',
                'last_run_option'   => 'dba_geo_portugal_last_run',
                'admin_slug'        => 'dba-geo-portugal',
            ),
        );
    }

    /**
     * Get a single country config.
     */
    public static function get_country( string $key ) {
        $countries = self::get_countries();
        return $countries[ $key ] ?? null;
    }

    /**
     * Get only enabled countries (those with settings where enabled = true).
     */
    public static function get_enabled_countries() {
        $enabled = array();
        foreach ( self::get_countries() as $key => $config ) {
            $settings = get_option( $config['settings_option'], array() );
            if ( ! empty( $settings['enabled'] ) ) {
                $enabled[ $key ] = $config;
            }
        }
        return $enabled;
    }

    /**
     * Get all country keys.
     */
    public static function get_country_keys() {
        return array_keys( self::get_countries() );
    }

    /**
     * Get communes for a country from wp_options.
     *
     * @param string $country_key
     * @return array [ { commune, code, departement, region, population }, ... ]
     */
    public static function get_communes( string $country_key ) {
        $config = self::get_country( $country_key );
        if ( ! $config ) return array();
        return get_option( $config['communes_option_key'], array() );
    }

    /**
     * Get commune names only.
     */
    public static function get_commune_names( string $country_key ) {
        return array_column( self::get_communes( $country_key ), 'commune' );
    }

    /**
     * Get active communes (subset selected in dashboard settings).
     */
    public static function get_active_communes( string $country_key ) {
        $config   = self::get_country( $country_key );
        $settings = get_option( $config['settings_option'], array() );
        $active   = $settings['active_communes'] ?? array();

        if ( empty( $active ) ) {
            // If none selected, return all
            return self::get_communes( $country_key );
        }

        $all = self::get_communes( $country_key );
        return array_filter( $all, function( $c ) use ( $active ) {
            return in_array( $c['commune'], $active, true );
        });
    }

    /**
     * Normalize commune name for dedupe (lowercase, accents stripped, hyphens normalized).
     */
    public static function normalize_commune( string $name ) {
        $name = mb_strtolower( trim( $name ), 'UTF-8' );
        // Transliterate accents
        if ( function_exists( 'iconv' ) ) {
            $conv = @iconv( 'UTF-8', 'ASCII//TRANSLIT//IGNORE', $name );
            if ( $conv ) $name = $conv;
        }
        $name = preg_replace( '/[^a-z0-9]+/', '-', $name );
        return trim( $name, '-' );
    }

    /**
     * Generate a slug from commune name.
     */
    public static function commune_slug( string $commune ) {
        return self::normalize_commune( $commune );
    }
}
