<?php
/**
 * DBA_TIS_Recommender — Strategic Content Recommendation Engine
 *
 * The brain that turns TIS scan data into actionable content directives.
 * Compares current topic distribution against strategic targets and
 * generates recommendations that can be:
 *   1. Displayed on the admin dashboard
 *   2. Fed into bots (LuxStrat, GeoBot, etc.) as forced theme priorities
 *   3. Injected into SEO Sniper keyword suggestions
 *   4. Used by Master Calendar for content planning
 *
 * Strategic targets are configurable: "Damalion must be #1 for X"
 * Each target has a topic slug, target keywords, and priority level.
 *
 * @since 2.17.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_TIS_Recommender {

    /** Option key for strategic targets */
    const TARGETS_KEY = 'dba_tis_targets';

    /** Option key for active recommendations */
    const RECS_KEY = 'dba_tis_recommendations';

    /** Option key for bot directives (consumed by generators) */
    const DIRECTIVES_KEY = 'dba_tis_bot_directives';

    /* ══════════════════════════════════════════════════════════════
     *  STRATEGIC TARGETS — "We must rank #1 for these"
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Get default strategic targets.
     */
    public static function get_default_targets() {
        return array(

            // ═══════════════════════════════════════════════════
            //  LUXSTRAT — English Luxembourg Structuring (11)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'lux_fund_services',
                'label'       => 'Luxembourg Fund Services',
                'topic_slug'  => 'investment_funds',
                'keywords'    => array( 'Luxembourg fund services', 'fund services Luxembourg', 'fund administration Luxembourg', 'Luxembourg investment fund', 'fund management company Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 15,
                'description' => 'Damalion must be #1 in Luxembourg Fund Services — the core business.',
            ),
            array(
                'id'          => 'setup_soparfi',
                'label'       => 'Setup of SOPARFI',
                'topic_slug'  => 'soparfi',
                'keywords'    => array( 'setup SOPARFI', 'create SOPARFI Luxembourg', 'SOPARFI holding company', 'SOPARFI formation', 'société de participations financières', 'Luxembourg SOPARFI' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 12,
                'description' => 'SOPARFI is the most popular Luxembourg holding structure. Must dominate SERPs.',
            ),
            array(
                'id'          => 'setup_raif',
                'label'       => 'Setup of Luxembourg RAIF',
                'topic_slug'  => 'raif',
                'keywords'    => array( 'Luxembourg RAIF', 'RAIF fund', 'reserved alternative investment fund', 'setup RAIF Luxembourg', 'create RAIF', 'RAIF vs SIF', 'FIAR Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 10,
                'description' => 'RAIF is the fastest-growing fund structure in Luxembourg. Key competitive differentiator.',
            ),
            array(
                'id'          => 'lux_sicav',
                'label'       => 'Luxembourg SICAV / UCITS',
                'topic_slug'  => 'ucits_sicav',
                'keywords'    => array( 'Luxembourg SICAV', 'UCITS fund Luxembourg', 'SICAV formation', 'create UCITS', 'Part II fund Luxembourg', 'SIF Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 8,
                'description' => 'SICAV/UCITS represent the largest fund market. Strong content presence required.',
            ),
            array(
                'id'          => 'lux_sicar',
                'label'       => 'Luxembourg SICAR',
                'topic_slug'  => 'sicar_securitization',
                'keywords'    => array( 'SICAR Luxembourg', 'create SICAR', 'SICAR fund', 'risk capital investment', 'société d\'investissement en capital à risque' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 6,
                'description' => 'SICAR for private equity and risk capital investors.',
            ),
            array(
                'id'          => 'lux_spf',
                'label'       => 'Luxembourg SPF',
                'topic_slug'  => 'spf',
                'keywords'    => array( 'SPF Luxembourg', 'private wealth management company', 'société de gestion de patrimoine familial', 'family wealth Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 5,
                'description' => 'SPF for HNWI family wealth structuring.',
            ),
            array(
                'id'          => 'lux_company_formation',
                'label'       => 'Luxembourg Company Formation',
                'topic_slug'  => 'company_formation',
                'keywords'    => array( 'company formation Luxembourg', 'create company Luxembourg', 'business setup Luxembourg', 'incorporate in Luxembourg', 'S.à r.l. Luxembourg', 'SA Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 15,
                'description' => 'Core gateway service. First touchpoint for most clients.',
            ),
            array(
                'id'          => 'lux_pe_vc',
                'label'       => 'Luxembourg Private Equity & VC',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'private equity Luxembourg', 'VC fund Luxembourg', 'PE fund structure', 'SCSp Luxembourg', 'carried interest Luxembourg', 'GP LP structure Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 8,
                'description' => 'Luxembourg is the #2 global fund domicile. PE/VC is a growth vertical.',
            ),
            array(
                'id'          => 'lux_scsp',
                'label'       => 'Luxembourg SCSp (Special Limited Partnership)',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'SCSp Luxembourg', 'special limited partnership Luxembourg', 'société en commandite spéciale', 'create SCSp', 'SCSp fund structure', 'SCSp vs SCA', 'SCSp carried interest', 'GP LP Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 6,
                'description' => 'SCSp is THE vehicle for PE/VC fund structuring in Luxembourg.',
            ),
            array(
                'id'          => 'lux_esg',
                'label'       => 'Luxembourg ESG & Sustainable Finance',
                'topic_slug'  => 'esg_sustainability',
                'keywords'    => array( 'ESG Luxembourg', 'sustainable finance Luxembourg', 'Article 8 fund', 'Article 9 fund', 'SFDR Luxembourg', 'green bond Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 5,
                'description' => 'Growing regulatory focus. Positions Damalion as forward-thinking.',
            ),
            array(
                'id'          => 'lux_domiciliation',
                'label'       => 'Luxembourg Domiciliation & Governance',
                'topic_slug'  => 'corporate_governance',
                'keywords'    => array( 'domiciliation Luxembourg', 'registered office Luxembourg', 'corporate governance Luxembourg', 'nominee director Luxembourg', 'substance Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'luxstrat',
                'min_pages'   => 5,
                'description' => 'Recurring revenue service. Critical for substance requirements.',
            ),

            // ═══════════════════════════════════════════════════
            //  COMFISC-FR — French Accounting & Tax (8)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'cf_creation_societe',
                'label'       => 'Création de société au Luxembourg',
                'topic_slug'  => 'c1_societe_creation',
                'keywords'    => array( 'création société Luxembourg', 'créer une entreprise au Luxembourg', 'immatriculer société Luxembourg', 'SARL Luxembourg création', 'société anonyme Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 10,
                'description' => 'Porte d\'entrée principale pour les clients francophones.',
            ),
            array(
                'id'          => 'cf_impot_societes',
                'label'       => 'Impôt sur les sociétés Luxembourg',
                'topic_slug'  => 'c2_impot_societes',
                'keywords'    => array( 'impôt sociétés Luxembourg', 'taux IRC Luxembourg', 'fiscalité entreprise Luxembourg', 'déclaration fiscale Luxembourg', 'impôt commercial communal' ),
                'priority'    => 'critical',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 8,
                'description' => 'Sujet n°1 en volume de recherche FR pour le Luxembourg fiscal.',
            ),
            array(
                'id'          => 'cf_tva',
                'label'       => 'TVA Luxembourg',
                'topic_slug'  => 'c2_tva_international',
                'keywords'    => array( 'TVA Luxembourg', 'taux TVA Luxembourg', 'déclaration TVA Luxembourg', 'TVA intracommunautaire Luxembourg', 'numéro TVA Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 6,
                'description' => 'TVA = recherche transactionnelle forte, haut volume.',
            ),
            array(
                'id'          => 'cf_comptes_annuels',
                'label'       => 'Comptes annuels et audit Luxembourg',
                'topic_slug'  => 'c3_comptes_annuels',
                'keywords'    => array( 'comptes annuels Luxembourg', 'dépôt comptes annuels RCS', 'bilan société Luxembourg', 'audit obligatoire Luxembourg', 'commissaire aux comptes Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 6,
                'description' => 'Obligation légale annuelle — fort trafic saisonnier.',
            ),
            array(
                'id'          => 'cf_holding',
                'label'       => 'Holding et SOPARFI (FR)',
                'topic_slug'  => 'c2_holding_structuration',
                'keywords'    => array( 'holding Luxembourg', 'SOPARFI avantages', 'créer holding Luxembourg', 'régime mère-fille Luxembourg', 'exonération dividendes Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 6,
                'description' => 'SOPARFI vu côté comptable/fiscal FR.',
            ),
            array(
                'id'          => 'cf_prix_transfert',
                'label'       => 'Prix de transfert Luxembourg',
                'topic_slug'  => 'c2_prix_transfert',
                'keywords'    => array( 'prix de transfert Luxembourg', 'transfer pricing Luxembourg', 'documentation prix transfert', 'BEPS Luxembourg', 'pleine concurrence Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 4,
                'description' => 'Sujet technique mais forte valeur pour les groupes internationaux.',
            ),
            array(
                'id'          => 'cf_paie',
                'label'       => 'Paie et droit du travail Luxembourg',
                'topic_slug'  => 'c3_paie_salaires',
                'keywords'    => array( 'fiche de paie Luxembourg', 'salaire minimum Luxembourg', 'charges sociales Luxembourg', 'contrat travail Luxembourg', 'CNS Luxembourg cotisations' ),
                'priority'    => 'medium',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 5,
                'description' => 'Fort volume de recherche FR, surtout transfrontaliers.',
            ),
            array(
                'id'          => 'cf_restructuration',
                'label'       => 'Restructuration et liquidation',
                'topic_slug'  => 'c4_restructuration_strategique',
                'keywords'    => array( 'liquidation société Luxembourg', 'dissolution société Luxembourg', 'restructuration entreprise Luxembourg', 'fusion société Luxembourg', 'fermer société Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'comfisc-fr',
                'min_pages'   => 4,
                'description' => 'Cycle de vie complet — souvent négligé par les concurrents.',
            ),

            // ═══════════════════════════════════════════════════
            //  LUXSTRAT-INTL-FR — French Luxembourg Structuring (6)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'fr_soparfi',
                'label'       => 'SOPARFI Luxembourg (FR)',
                'topic_slug'  => 'soparfi',
                'keywords'    => array( 'créer SOPARFI Luxembourg', 'SOPARFI avantages fiscaux', 'holding SOPARFI', 'SOPARFI société de participations' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 8,
                'description' => 'SOPARFI pour audience francophone — structuration, pas comptabilité.',
            ),
            array(
                'id'          => 'fr_raif',
                'label'       => 'Fonds RAIF Luxembourg (FR)',
                'topic_slug'  => 'raif',
                'keywords'    => array( 'RAIF Luxembourg', 'fonds RAIF', 'créer RAIF Luxembourg', 'FIAR Luxembourg', 'fonds alternatif réservé Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 6,
                'description' => 'RAIF en français pour investisseurs francophones.',
            ),
            array(
                'id'          => 'fr_scsp',
                'label'       => 'SCSp Luxembourg (FR)',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'SCSp Luxembourg', 'société en commandite spéciale', 'créer SCSp', 'SCSp private equity', 'SCSp fonds Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 5,
                'description' => 'SCSp est le véhicule PE/VC par excellence au Luxembourg.',
            ),
            array(
                'id'          => 'fr_sicav',
                'label'       => 'SICAV et UCITS Luxembourg (FR)',
                'topic_slug'  => 'ucits_sicav',
                'keywords'    => array( 'SICAV Luxembourg', 'fonds UCITS Luxembourg', 'créer SICAV', 'OPCVM Luxembourg', 'fonds Partie II Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 5,
                'description' => 'SICAV/UCITS en français.',
            ),
            array(
                'id'          => 'fr_company',
                'label'       => 'Création société Luxembourg (FR structuration)',
                'topic_slug'  => 'company_formation',
                'keywords'    => array( 'créer société Luxembourg', 'constitution société Luxembourg', 'SARL Luxembourg', 'SA Luxembourg', 'immatriculation RCS Luxembourg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 8,
                'description' => 'Création société côté structuration (vs comptabilité pour comfisc).',
            ),
            array(
                'id'          => 'fr_pe',
                'label'       => 'Private Equity Luxembourg (FR)',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'private equity Luxembourg', 'fonds PE Luxembourg', 'capital investissement Luxembourg', 'structurer fonds PE Luxembourg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-fr',
                'min_pages'   => 5,
                'description' => 'PE/VC pour audience francophone.',
            ),

            // ═══════════════════════════════════════════════════
            //  LUXSTRAT-INTL-DE — German Luxembourg Structuring (5)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'de_soparfi',
                'label'       => 'SOPARFI Luxemburg (DE)',
                'topic_slug'  => 'soparfi',
                'keywords'    => array( 'SOPARFI Luxemburg', 'SOPARFI gründen', 'Holdinggesellschaft Luxemburg', 'SOPARFI Vorteile', 'SOPARFI Steuervorteile' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-de',
                'min_pages'   => 6,
                'description' => 'SOPARFI für deutschsprachige Investoren.',
            ),
            array(
                'id'          => 'de_raif',
                'label'       => 'RAIF Luxemburg (DE)',
                'topic_slug'  => 'raif',
                'keywords'    => array( 'RAIF Luxemburg', 'RAIF Fonds', 'reservierter alternativer Investmentfonds', 'RAIF gründen Luxemburg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-de',
                'min_pages'   => 5,
                'description' => 'RAIF auf Deutsch.',
            ),
            array(
                'id'          => 'de_company',
                'label'       => 'Firmengründung Luxemburg (DE)',
                'topic_slug'  => 'company_formation',
                'keywords'    => array( 'Firma gründen Luxemburg', 'Firmengründung Luxemburg', 'GmbH Luxemburg', 'S.à r.l. Luxemburg', 'Unternehmen gründen Luxemburg' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-de',
                'min_pages'   => 6,
                'description' => 'Firmengründung — Haupteinstiegspunkt für DACH-Kunden.',
            ),
            array(
                'id'          => 'de_pe',
                'label'       => 'Private Equity Luxemburg (DE)',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'Private Equity Luxemburg', 'PE Fonds Luxemburg', 'SCSp Luxemburg', 'Fondsstrukturierung Luxemburg' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-de',
                'min_pages'   => 4,
                'description' => 'PE/VC für deutschsprachige Fondsmanager.',
            ),
            array(
                'id'          => 'de_domiciliation',
                'label'       => 'Domizilierung Luxemburg (DE)',
                'topic_slug'  => 'corporate_governance',
                'keywords'    => array( 'Domizilierung Luxemburg', 'Firmensitz Luxemburg', 'Registered Office Luxemburg', 'Substanz Luxemburg' ),
                'priority'    => 'medium',
                'target_bot'  => 'luxstrat-intl-de',
                'min_pages'   => 3,
                'description' => 'Domizilierung und Substanzanforderungen auf Deutsch.',
            ),

            // ═══════════════════════════════════════════════════
            //  LUXSTRAT-INTL-PT — Portuguese Luxembourg Structuring (4)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'pt_soparfi',
                'label'       => 'SOPARFI Luxemburgo (PT)',
                'topic_slug'  => 'soparfi',
                'keywords'    => array( 'SOPARFI Luxemburgo', 'criar SOPARFI', 'holding Luxemburgo', 'SOPARFI vantagens fiscais' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-pt',
                'min_pages'   => 5,
                'description' => 'SOPARFI para investidores lusófonos.',
            ),
            array(
                'id'          => 'pt_raif',
                'label'       => 'RAIF Luxemburgo (PT)',
                'topic_slug'  => 'raif',
                'keywords'    => array( 'RAIF Luxemburgo', 'fundo RAIF', 'criar RAIF Luxemburgo', 'fundo alternativo reservado' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-pt',
                'min_pages'   => 4,
                'description' => 'RAIF em português.',
            ),
            array(
                'id'          => 'pt_company',
                'label'       => 'Criar empresa Luxemburgo (PT)',
                'topic_slug'  => 'company_formation',
                'keywords'    => array( 'criar empresa Luxemburgo', 'abrir empresa Luxemburgo', 'sociedade Luxemburgo', 'S.à r.l. Luxemburgo' ),
                'priority'    => 'critical',
                'target_bot'  => 'luxstrat-intl-pt',
                'min_pages'   => 5,
                'description' => 'Criação de empresa — entrada principal para clientes lusófonos.',
            ),
            array(
                'id'          => 'pt_pe',
                'label'       => 'Private Equity Luxemburgo (PT)',
                'topic_slug'  => 'private_equity',
                'keywords'    => array( 'private equity Luxemburgo', 'fundo PE Luxemburgo', 'SCSp Luxemburgo', 'estruturação fundos Luxemburgo' ),
                'priority'    => 'high',
                'target_bot'  => 'luxstrat-intl-pt',
                'min_pages'   => 3,
                'description' => 'PE/VC para gestores de fundos lusófonos.',
            ),

            // ═══════════════════════════════════════════════════
            //  GEOBOT — Country-Specific Investment Articles (6)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'geo_france',
                'label'       => 'Open a Company in France',
                'topic_slug'  => 'france',
                'keywords'    => array( 'open company France', 'company formation France', 'SAS France', 'SARL France', 'business setup France', 'register company France' ),
                'priority'    => 'critical',
                'target_bot'  => 'geobot',
                'min_pages'   => 10,
                'description' => 'France is the #1 market for Damalion geo content.',
            ),
            array(
                'id'          => 'geo_italy',
                'label'       => 'Open a Company in Italy',
                'topic_slug'  => 'italy',
                'keywords'    => array( 'open company Italy', 'company formation Italy', 'SRL Italy', 'business setup Italy', 'register company Italy' ),
                'priority'    => 'high',
                'target_bot'  => 'geobot',
                'min_pages'   => 8,
                'description' => 'Italy — strong demand from international investors.',
            ),
            array(
                'id'          => 'geo_spain',
                'label'       => 'Open a Company in Spain',
                'topic_slug'  => 'spain',
                'keywords'    => array( 'open company Spain', 'company formation Spain', 'SL Spain', 'business setup Spain', 'register company Spain' ),
                'priority'    => 'high',
                'target_bot'  => 'geobot',
                'min_pages'   => 8,
                'description' => 'Spain — gateway to Latin American business.',
            ),
            array(
                'id'          => 'geo_portugal',
                'label'       => 'Open a Company in Portugal',
                'topic_slug'  => 'portugal',
                'keywords'    => array( 'open company Portugal', 'company formation Portugal', 'LDA Portugal', 'business setup Portugal', 'NHR Portugal' ),
                'priority'    => 'medium',
                'target_bot'  => 'geobot',
                'min_pages'   => 6,
                'description' => 'Portugal — NHR regime and golden visa attract investors.',
            ),
            array(
                'id'          => 'geo_uk',
                'label'       => 'Open a Company in the UK',
                'topic_slug'  => 'uk',
                'keywords'    => array( 'open company UK', 'company formation UK', 'LTD UK', 'register company UK', 'Companies House UK' ),
                'priority'    => 'medium',
                'target_bot'  => 'geobot',
                'min_pages'   => 6,
                'description' => 'UK post-Brexit — strong redomiciliation interest.',
            ),
            array(
                'id'          => 'geo_germany',
                'label'       => 'Open a Company in Germany',
                'topic_slug'  => 'germany',
                'keywords'    => array( 'open company Germany', 'company formation Germany', 'GmbH Germany', 'business setup Germany', 'register company Germany' ),
                'priority'    => 'high',
                'target_bot'  => 'geobot',
                'min_pages'   => 8,
                'description' => 'Germany — largest EU economy, high search volume.',
            ),

            // ═══════════════════════════════════════════════════
            //  STARTUP-HUB — US Startup Content (8)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'sh_fintech',
                'label'       => 'Fintech Startup Formation',
                'topic_slug'  => 'fintech',
                'keywords'    => array( 'fintech startup', 'start a fintech company', 'fintech company formation', 'fintech license', 'payment startup formation' ),
                'priority'    => 'critical',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 8,
                'description' => 'Fintech is the largest startup vertical by search volume.',
            ),
            array(
                'id'          => 'sh_saas',
                'label'       => 'SaaS Company Formation',
                'topic_slug'  => 'saas',
                'keywords'    => array( 'start a SaaS company', 'SaaS startup formation', 'SaaS business structure', 'SaaS company Delaware', 'SaaS incorporation' ),
                'priority'    => 'high',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 6,
                'description' => 'SaaS — high-value recurring clients.',
            ),
            array(
                'id'          => 'sh_aiml',
                'label'       => 'AI & ML Startup Formation',
                'topic_slug'  => 'ai-ml',
                'keywords'    => array( 'AI startup formation', 'start an AI company', 'machine learning startup', 'AI company incorporation', 'AI startup funding' ),
                'priority'    => 'high',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 6,
                'description' => 'AI/ML — fastest growing startup category.',
            ),
            array(
                'id'          => 'sh_biotech',
                'label'       => 'Biotech Startup Formation',
                'topic_slug'  => 'biotech',
                'keywords'    => array( 'biotech startup', 'start a biotech company', 'biotech company formation', 'biotech incorporation', 'biotech startup funding' ),
                'priority'    => 'high',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 5,
                'description' => 'Biotech — high-value niche, complex structuring needs.',
            ),
            array(
                'id'          => 'sh_cleantech',
                'label'       => 'Cleantech & GreenTech Startups',
                'topic_slug'  => 'cleantech',
                'keywords'    => array( 'cleantech startup', 'green tech company formation', 'sustainable startup', 'clean energy startup', 'ESG startup formation' ),
                'priority'    => 'medium',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 4,
                'description' => 'Cleantech aligns with ESG trend.',
            ),
            array(
                'id'          => 'sh_healthtech',
                'label'       => 'HealthTech Startup Formation',
                'topic_slug'  => 'healthtech',
                'keywords'    => array( 'healthtech startup', 'digital health company', 'health tech company formation', 'telemedicine startup', 'healthtech incorporation' ),
                'priority'    => 'medium',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 4,
                'description' => 'HealthTech — post-pandemic growth sector.',
            ),
            array(
                'id'          => 'sh_cyber',
                'label'       => 'Cybersecurity Startup Formation',
                'topic_slug'  => 'cybersecurity',
                'keywords'    => array( 'cybersecurity startup', 'start a cybersecurity company', 'infosec company formation', 'cybersecurity business structure' ),
                'priority'    => 'medium',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 4,
                'description' => 'Cybersecurity — strong B2B demand.',
            ),
            array(
                'id'          => 'sh_web3',
                'label'       => 'Web3 & Blockchain Startup Formation',
                'topic_slug'  => 'web3',
                'keywords'    => array( 'web3 startup', 'blockchain company formation', 'crypto startup incorporation', 'DAO formation', 'web3 company structure' ),
                'priority'    => 'medium',
                'target_bot'  => 'startup-hub',
                'min_pages'   => 4,
                'description' => 'Web3 — niche but high-value structuring.',
            ),

            // ═══════════════════════════════════════════════════
            //  LATAM — Latin America Business (8)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'la_brazil',
                'label'       => 'Open a Company in Brazil',
                'topic_slug'  => 'brazil',
                'keywords'    => array( 'open company Brazil', 'company formation Brazil', 'LTDA Brazil', 'business setup Brazil', 'register company Brazil', 'abrir empresa Brasil' ),
                'priority'    => 'critical',
                'target_bot'  => 'latam',
                'min_pages'   => 8,
                'description' => 'Brazil — largest LATAM economy.',
            ),
            array(
                'id'          => 'la_mexico',
                'label'       => 'Open a Company in Mexico',
                'topic_slug'  => 'mexico',
                'keywords'    => array( 'open company Mexico', 'company formation Mexico', 'SA de CV Mexico', 'business setup Mexico', 'crear empresa México' ),
                'priority'    => 'critical',
                'target_bot'  => 'latam',
                'min_pages'   => 8,
                'description' => 'Mexico — #2 LATAM economy, nearshoring boom.',
            ),
            array(
                'id'          => 'la_colombia',
                'label'       => 'Open a Company in Colombia',
                'topic_slug'  => 'colombia',
                'keywords'    => array( 'open company Colombia', 'company formation Colombia', 'SAS Colombia', 'business setup Colombia', 'crear empresa Colombia' ),
                'priority'    => 'high',
                'target_bot'  => 'latam',
                'min_pages'   => 6,
                'description' => 'Colombia — fastest growing LATAM market for foreign investment.',
            ),
            array(
                'id'          => 'la_chile',
                'label'       => 'Open a Company in Chile',
                'topic_slug'  => 'chile',
                'keywords'    => array( 'open company Chile', 'company formation Chile', 'SpA Chile', 'business setup Chile', 'crear empresa Chile' ),
                'priority'    => 'high',
                'target_bot'  => 'latam',
                'min_pages'   => 5,
                'description' => 'Chile — most business-friendly LATAM country.',
            ),
            array(
                'id'          => 'la_argentina',
                'label'       => 'Open a Company in Argentina',
                'topic_slug'  => 'argentina',
                'keywords'    => array( 'open company Argentina', 'company formation Argentina', 'SA Argentina', 'SRL Argentina', 'business setup Argentina' ),
                'priority'    => 'medium',
                'target_bot'  => 'latam',
                'min_pages'   => 5,
                'description' => 'Argentina — large economy despite volatility.',
            ),
            array(
                'id'          => 'la_peru',
                'label'       => 'Open a Company in Peru',
                'topic_slug'  => 'peru',
                'keywords'    => array( 'open company Peru', 'company formation Peru', 'SAC Peru', 'business setup Peru', 'crear empresa Perú' ),
                'priority'    => 'medium',
                'target_bot'  => 'latam',
                'min_pages'   => 4,
                'description' => 'Peru — mining and natural resources attract foreign investment.',
            ),
            array(
                'id'          => 'la_costa_rica',
                'label'       => 'Open a Company in Costa Rica',
                'topic_slug'  => 'costa_rica',
                'keywords'    => array( 'open company Costa Rica', 'company formation Costa Rica', 'SRL Costa Rica', 'business setup Costa Rica' ),
                'priority'    => 'medium',
                'target_bot'  => 'latam',
                'min_pages'   => 3,
                'description' => 'Costa Rica — tech hub of Central America.',
            ),
            array(
                'id'          => 'la_ecuador',
                'label'       => 'Open a Company in Ecuador',
                'topic_slug'  => 'ecuador',
                'keywords'    => array( 'open company Ecuador', 'company formation Ecuador', 'business setup Ecuador', 'crear empresa Ecuador' ),
                'priority'    => 'low',
                'target_bot'  => 'latam',
                'min_pages'   => 3,
                'description' => 'Ecuador — dollarized economy, growing interest.',
            ),

            // ═══════════════════════════════════════════════════
            //  EEUROPE — Eastern Europe Investment (6)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'ee_poland',
                'label'       => 'Open a Company in Poland',
                'topic_slug'  => 'poland',
                'keywords'    => array( 'open company Poland', 'company formation Poland', 'sp. z o.o. Poland', 'business setup Poland', 'register company Poland' ),
                'priority'    => 'critical',
                'target_bot'  => 'eeurope',
                'min_pages'   => 6,
                'description' => 'Poland — largest Eastern European economy.',
            ),
            array(
                'id'          => 'ee_romania',
                'label'       => 'Open a Company in Romania',
                'topic_slug'  => 'romania',
                'keywords'    => array( 'open company Romania', 'company formation Romania', 'SRL Romania', 'business setup Romania', 'register company Romania' ),
                'priority'    => 'high',
                'target_bot'  => 'eeurope',
                'min_pages'   => 5,
                'description' => 'Romania — fast-growing EU economy, 1% micro-enterprise tax.',
            ),
            array(
                'id'          => 'ee_czech',
                'label'       => 'Open a Company in Czech Republic',
                'topic_slug'  => 'czech_republic',
                'keywords'    => array( 'open company Czech Republic', 'company formation Czech Republic', 's.r.o. Czech', 'business setup Prague' ),
                'priority'    => 'high',
                'target_bot'  => 'eeurope',
                'min_pages'   => 5,
                'description' => 'Czech Republic — stable, well-regulated business environment.',
            ),
            array(
                'id'          => 'ee_hungary',
                'label'       => 'Open a Company in Hungary',
                'topic_slug'  => 'hungary',
                'keywords'    => array( 'open company Hungary', 'company formation Hungary', 'Kft Hungary', 'business setup Hungary', 'register company Budapest' ),
                'priority'    => 'medium',
                'target_bot'  => 'eeurope',
                'min_pages'   => 4,
                'description' => 'Hungary — 9% corporate tax rate attracts investors.',
            ),
            array(
                'id'          => 'ee_bulgaria',
                'label'       => 'Open a Company in Bulgaria',
                'topic_slug'  => 'bulgaria',
                'keywords'    => array( 'open company Bulgaria', 'company formation Bulgaria', 'EOOD Bulgaria', 'business setup Bulgaria', '10% flat tax Bulgaria' ),
                'priority'    => 'medium',
                'target_bot'  => 'eeurope',
                'min_pages'   => 4,
                'description' => 'Bulgaria — lowest EU corporate tax at 10%.',
            ),
            array(
                'id'          => 'ee_serbia',
                'label'       => 'Open a Company in Serbia',
                'topic_slug'  => 'serbia',
                'keywords'    => array( 'open company Serbia', 'company formation Serbia', 'DOO Serbia', 'business setup Serbia', 'invest in Serbia' ),
                'priority'    => 'low',
                'target_bot'  => 'eeurope',
                'min_pages'   => 3,
                'description' => 'Serbia — emerging EU candidate with growing FDI.',
            ),

            // ═══════════════════════════════════════════════════
            //  NEWSBOT — PE/Capital Markets News (3)
            // ═══════════════════════════════════════════════════
            array(
                'id'          => 'nb_pe_news',
                'label'       => 'Private Equity News Europe',
                'topic_slug'  => 'pe_news',
                'keywords'    => array( 'private equity news Europe', 'PE deals Europe', 'private equity Luxembourg news', 'buyout news Europe', 'PE fundraising Europe' ),
                'priority'    => 'high',
                'target_bot'  => 'newsbot',
                'min_pages'   => 5,
                'description' => 'PE news keeps Damalion visible in current deal flow.',
            ),
            array(
                'id'          => 'nb_capital_markets',
                'label'       => 'Capital Markets Luxembourg',
                'topic_slug'  => 'pe_news',
                'keywords'    => array( 'capital markets Luxembourg', 'Luxembourg Stock Exchange', 'LuxSE green bonds', 'bond listing Luxembourg', 'Euro MTF listing' ),
                'priority'    => 'high',
                'target_bot'  => 'newsbot',
                'min_pages'   => 4,
                'description' => 'Capital markets content supports fund services positioning.',
            ),
            array(
                'id'          => 'nb_regulatory_news',
                'label'       => 'CSSF & EU Regulatory Updates',
                'topic_slug'  => 'pe_news',
                'keywords'    => array( 'CSSF circular', 'EU fund regulation update', 'AIFMD II', 'ELTIF 2.0', 'DORA Luxembourg' ),
                'priority'    => 'medium',
                'target_bot'  => 'newsbot',
                'min_pages'   => 3,
                'description' => 'Regulatory news establishes authority.',
            ),
        );
    }

    /**
     * Get active targets (custom or default).
     */
    public static function get_targets() {
        $custom = get_option( self::TARGETS_KEY, array() );
        return ! empty( $custom ) ? $custom : self::get_default_targets();
    }

    /**
     * Save custom targets.
     */
    public static function save_targets( $targets ) {
        update_option( self::TARGETS_KEY, $targets, false );
    }

    /**
     * Add a new target.
     */
    public static function add_target( $target ) {
        $targets = self::get_targets();
        $target['id'] = sanitize_key( $target['id'] ?? wp_generate_uuid4() );
        $targets[] = $target;
        self::save_targets( $targets );
        return $target;
    }

    /**
     * Remove a target by ID.
     */
    public static function remove_target( $id ) {
        $targets = self::get_targets();
        $targets = array_filter( $targets, function( $t ) use ( $id ) {
            return $t['id'] !== $id;
        } );
        self::save_targets( array_values( $targets ) );
    }

    /* ══════════════════════════════════════════════════════════════
     *  RECOMMENDATION GENERATOR
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Generate recommendations from scan results.
     *
     * @param  array $scan_results  Results from DBA_TIS_Analyzer::run_scan().
     * @return array                Array of recommendations.
     */
    public static function generate_recommendations( $scan_results ) {
        if ( empty( $scan_results ) || is_wp_error( $scan_results ) ) {
            return array();
        }

        // Timeout guard — 72 targets × 2135 pages is CPU-intensive
        if ( function_exists( 'set_time_limit' ) ) @set_time_limit( 300 );
        if ( function_exists( 'ignore_user_abort' ) ) @ignore_user_abort( true );

        $recs = array();
        $distribution   = $scan_results['distribution'] ?? array();
        $target_analysis = $scan_results['target_analysis'] ?? array();

        // ─── 1. TARGET GAP RECOMMENDATIONS ───
        foreach ( $target_analysis as $target_id => $analysis ) {
            $target  = $analysis['target'];
            $grade   = $analysis['coverage_grade'];
            $pages   = $analysis['covering_pages'];
            $min     = $target['min_pages'] ?? 10;

            if ( $grade === 'A' && $pages >= $min ) {
                // Good coverage — push Kaizen refresh to keep content fresh
                $recs[] = array(
                    'type'     => 'maintain',
                    'priority' => 'low',
                    'target'   => $target['label'],
                    'grade'    => $grade,
                    'icon'     => '✅',
                    'title'    => $target['label'] . ' — Strong coverage (Grade ' . $grade . ')',
                    'message'  => $pages . ' pages cover this topic. Pushing Kaizen refresh for oldest content.',
                    'action'   => 'kaizen_refresh',
                    'details'  => array(
                        'target_bot'     => $target['target_bot'] ?? 'luxstrat',
                        'pages_found'    => $pages,
                        'pages_required' => $min,
                        'keywords'       => $target['keywords'],
                        'kw_in_titles'   => $analysis['kw_in_titles'],
                    ),
                );
            } elseif ( $grade === 'F' || $grade === 'D' ) {
                // Critical gap — urgent content needed
                $pages_needed = max( 0, $min - $pages );
                $recs[] = array(
                    'type'     => 'critical_gap',
                    'priority' => $target['priority'],
                    'target'   => $target['label'],
                    'grade'    => $grade,
                    'icon'     => '🔴',
                    'title'    => '🚨 ' . $target['label'] . ' — Critical content gap (Grade ' . $grade . ')',
                    'message'  => 'Only ' . $pages . '/' . $min . ' pages found. Need ' . $pages_needed . ' more pages targeting: ' . implode( ', ', $target['keywords'] ),
                    'action'   => 'generate_batch',
                    'details'  => array(
                        'pages_found'    => $pages,
                        'pages_required' => $min,
                        'pages_to_create' => $pages_needed,
                        'target_bot'     => $target['target_bot'],
                        'keywords'       => $target['keywords'],
                        'kw_in_titles'   => $analysis['kw_in_titles'],
                    ),
                );
            } elseif ( $grade === 'C' || $grade === 'B' ) {
                // Moderate gap — strategic enhancement needed
                $pages_needed = max( 0, $min - $pages );
                $recs[] = array(
                    'type'     => 'enhance',
                    'priority' => $target['priority'] === 'critical' ? 'high' : 'medium',
                    'target'   => $target['label'],
                    'grade'    => $grade,
                    'icon'     => '🟡',
                    'title'    => $target['label'] . ' — Needs enhancement (Grade ' . $grade . ')',
                    'message'  => $pages . '/' . $min . ' pages found. Create ' . $pages_needed . ' more and optimize existing titles/headings for: ' . implode( ', ', array_slice( $target['keywords'], 0, 3 ) ),
                    'action'   => 'enhance_and_generate',
                    'details'  => array(
                        'pages_found'     => $pages,
                        'pages_required'  => $min,
                        'pages_to_create' => $pages_needed,
                        'target_bot'      => $target['target_bot'],
                        'keywords'        => $target['keywords'],
                        'kw_in_titles'    => $analysis['kw_in_titles'],
                        'kw_in_headings'  => $analysis['kw_in_headings'],
                    ),
                );
            }
        }

        // ─── 2. TOPIC IMBALANCE RECOMMENDATIONS ───
        $dist_values = array_column( $distribution, 'percentage' );
        if ( ! empty( $dist_values ) ) {
            $max_pct = max( $dist_values );
            $dominance_threshold = 35; // If one topic > 35% it's dominating

            // Pre-load targets + build slug index (avoids repeated get_targets in loop)
            $targets = self::get_targets();
            $targets_by_slug = array();
            foreach ( $targets as $t ) {
                $s = $t['topic_slug'] ?? '';
                if ( ! isset( $targets_by_slug[ $s ] ) ) $targets_by_slug[ $s ] = array();
                $targets_by_slug[ $s ][] = $t;
            }

            foreach ( $distribution as $slug => $data ) {
                if ( $slug === 'other' ) continue;

                // Warn if a non-strategic topic is dominating
                if ( $data['percentage'] > $dominance_threshold ) {
                    // Check if this is a strategic target
                    $is_strategic = false;
                    $slug_targets = $targets_by_slug[ $slug ] ?? array();
                    foreach ( $slug_targets as $t ) {
                        if ( in_array( $t['priority'], array( 'critical', 'high' ) ) ) {
                            $is_strategic = true;
                            break;
                        }
                    }

                    if ( ! $is_strategic ) {
                        // ── Find which bot produces this over-covered topic ──
                        $rebal_bot = 'luxstrat'; // default
                        foreach ( $slug_targets as $t ) {
                            $rebal_bot = $t['target_bot'];
                            break;
                        }

                        $recs[] = array(
                            'type'     => 'rebalance',
                            'priority' => 'medium',
                            'target'   => $data['label'],
                            'grade'    => null,
                            'icon'     => '⚖️',
                            'title'    => 'Topic imbalance: ' . $data['label'] . ' dominates at ' . $data['percentage'] . '%',
                            'message'  => 'Pushing DEPRIORITISE directive. Bots will avoid this topic until balance improves.',
                            'action'   => 'deprioritise',
                            'details'  => array(
                                'target_bot' => $rebal_bot,
                                'topic'      => $slug,
                                'keywords'   => array( $data['label'] ),
                                'percentage' => $data['percentage'],
                                'page_count' => $data['page_count'],
                            ),
                        );
                    }
                }

                // Flag topics with zero content — AUTO-ESCALATE to actionable directive
                if ( $data['page_count'] === 0 && $slug !== 'other' ) {
                    // ── Determine best bot and keywords for this blind spot ──
                    $blind_bot      = 'luxstrat'; // default
                    $blind_keywords = array();
                    $blind_priority = 'high'; // blind spots are never "low" — zero pages = action needed

                    // Check if this blind spot matches a strategic target
                    $slug_targets = $targets_by_slug[ $slug ] ?? array();
                    $matched_target = false;
                    foreach ( $slug_targets as $t ) {
                        $blind_bot      = $t['target_bot'];
                        $blind_keywords = $t['keywords'];
                        $blind_priority = $t['priority'];
                        $matched_target = true;
                        break;
                    }

                    // If no target match, derive keywords from the topic taxonomy label
                    if ( empty( $blind_keywords ) ) {
                        $taxonomy = class_exists( 'DBA_TIS_Analyzer' ) ? DBA_TIS_Analyzer::get_taxonomy() : array();
                        if ( isset( $taxonomy[ $slug ] ) ) {
                            $blind_keywords = $taxonomy[ $slug ]['keywords'] ?? array();
                        }
                        if ( empty( $blind_keywords ) ) {
                            // Fallback: split label into keyword phrases
                            $blind_keywords = array( $data['label'] . ' Luxembourg' );
                        }
                    }

                    $recs[] = array(
                        'type'     => 'blind_spot',
                        'priority' => $blind_priority,
                        'target'   => $data['label'],
                        'grade'    => 'F',
                        'icon'     => '🔴',
                        'title'    => '🚨 Blind spot: ' . $data['label'] . ' — Zero dedicated pages',
                        'message'  => 'No pages cover this topic. Creating content immediately. Targeting: ' . implode( ', ', array_slice( $blind_keywords, 0, 5 ) ),
                        'action'   => 'generate_batch',
                        'details'  => array(
                            'topic'           => $slug,
                            'target_bot'      => $blind_bot,
                            'keywords'        => $blind_keywords,
                            'pages_to_create' => $matched_target ? 5 : 3,
                        ),
                    );
                }
            }
        }

        // ─── 3. SEO TITLE OPTIMIZATION — PUSH TO KAIZEN ───
        foreach ( $target_analysis as $target_id => $analysis ) {
            $target = $analysis['target'];
            if ( $analysis['kw_in_titles'] < 3 && $analysis['covering_pages'] >= 5 ) {
                $recs[] = array(
                    'type'     => 'seo_optimize',
                    'priority' => 'high',
                    'target'   => $target['label'],
                    'grade'    => null,
                    'icon'     => '🔍',
                    'title'    => 'SEO gap: "' . $target['label'] . '" — Only ' . $analysis['kw_in_titles'] . ' pages have keywords in titles',
                    'message'  => 'Pushing title optimization to Kaizen Center for ' . ( $analysis['covering_pages'] - $analysis['kw_in_titles'] ) . ' pages. Target keywords: ' . implode( ', ', array_slice( $target['keywords'], 0, 3 ) ),
                    'action'   => 'kaizen_optimize_titles',
                    'details'  => array(
                        'target_bot'    => $target['target_bot'] ?? 'luxstrat',
                        'keywords'      => $target['keywords'],
                        'pages_to_fix'  => $analysis['covering_pages'] - $analysis['kw_in_titles'],
                    ),
                );
            }
        }

        // Sort by priority
        $priority_order = array( 'critical' => 0, 'high' => 1, 'medium' => 2, 'low' => 3 );
        usort( $recs, function( $a, $b ) use ( $priority_order ) {
            $pa = $priority_order[ $a['priority'] ] ?? 4;
            $pb = $priority_order[ $b['priority'] ] ?? 4;
            return $pa <=> $pb;
        } );

        // Store recommendations
        update_option( self::RECS_KEY, array(
            'generated_at'     => current_time( 'mysql' ),
            'recommendations'  => $recs,
            'summary'          => self::generate_summary( $recs ),
        ), false );

        return $recs;
    }

    /* ══════════════════════════════════════════════════════════════
     *  BOT DIRECTIVES — Actionable instructions for generators
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Generate bot directives from recommendations.
     * EVERY recommendation type produces an actionable directive.
     *
     * Directive types pushed:
     *   - critical_gap   → Bot: CREATE new articles (urgent)
     *   - enhance        → Bot: CREATE + optimise existing
     *   - blind_spot     → Bot: CREATE from scratch (auto-escalated)
     *   - seo_optimize   → Kaizen: FIX titles on existing posts
     *   - maintain       → Kaizen: REFRESH oldest content
     *   - rebalance      → Bot: DEPRIORITISE over-covered topic
     *
     * Format: array of [ bot => directive[] ]
     */
    public static function generate_bot_directives( $recommendations ) {
        $directives = array();

        foreach ( $recommendations as $rec ) {
            $bot = $rec['details']['target_bot'] ?? '';

            switch ( $rec['type'] ) {

                // ── CREATE directives: push to content bots ──
                case 'critical_gap':
                case 'enhance':
                case 'enhance_and_generate':
                case 'blind_spot':
                    if ( empty( $bot ) ) $bot = 'luxstrat'; // fallback
                    if ( ! isset( $directives[ $bot ] ) ) $directives[ $bot ] = array();

                    $directives[ $bot ][] = array(
                        'directive_type'  => 'create',
                        'target_label'    => $rec['target'],
                        'keywords'        => $rec['details']['keywords'] ?? array(),
                        'urgency'         => $rec['priority'],
                        'pages_to_create' => $rec['details']['pages_to_create'] ?? 3,
                        'grade'           => $rec['grade'],
                        'instruction'     => self::build_bot_instruction( $rec ),
                    );
                    break;

                // ── SEO TITLE FIX: push to Kaizen Center ──
                case 'seo_optimize':
                    $kaizen_bot = 'kaizen';
                    if ( ! isset( $directives[ $kaizen_bot ] ) ) $directives[ $kaizen_bot ] = array();

                    $directives[ $kaizen_bot ][] = array(
                        'directive_type' => 'optimize_titles',
                        'target_label'   => $rec['target'],
                        'keywords'       => $rec['details']['keywords'] ?? array(),
                        'urgency'        => $rec['priority'],
                        'pages_to_fix'   => $rec['details']['pages_to_fix'] ?? 0,
                        'grade'          => $rec['grade'],
                        'source_bot'     => $rec['details']['target_bot'] ?? 'luxstrat',
                        'instruction'    => self::build_bot_instruction( $rec ),
                    );
                    break;

                // ── REFRESH: push to Kaizen Center ──
                case 'maintain':
                    $kaizen_bot = 'kaizen';
                    if ( ! isset( $directives[ $kaizen_bot ] ) ) $directives[ $kaizen_bot ] = array();

                    $directives[ $kaizen_bot ][] = array(
                        'directive_type' => 'refresh',
                        'target_label'   => $rec['target'],
                        'keywords'       => $rec['details']['keywords'] ?? array(),
                        'urgency'        => 'low',
                        'grade'          => $rec['grade'],
                        'source_bot'     => $rec['details']['target_bot'] ?? 'luxstrat',
                        'instruction'    => self::build_bot_instruction( $rec ),
                    );
                    break;

                // ── DEPRIORITISE: push to content bots ──
                case 'rebalance':
                    if ( empty( $bot ) ) $bot = 'luxstrat';
                    if ( ! isset( $directives[ $bot ] ) ) $directives[ $bot ] = array();

                    $directives[ $bot ][] = array(
                        'directive_type' => 'deprioritise',
                        'target_label'   => $rec['target'],
                        'keywords'       => $rec['details']['keywords'] ?? array(),
                        'urgency'        => 'medium',
                        'percentage'     => $rec['details']['percentage'] ?? 0,
                        'grade'          => null,
                        'instruction'    => self::build_bot_instruction( $rec ),
                    );
                    break;
            }
        }

        // Sort directives by urgency within each bot
        $urgency_order = array( 'critical' => 0, 'high' => 1, 'medium' => 2, 'low' => 3 );
        foreach ( $directives as $bot => &$dirs ) {
            usort( $dirs, function( $a, $b ) use ( $urgency_order ) {
                return ( $urgency_order[ $a['urgency'] ] ?? 4 ) <=> ( $urgency_order[ $b['urgency'] ] ?? 4 );
            } );
        }
        unset( $dirs );

        update_option( self::DIRECTIVES_KEY, array(
            'generated_at' => current_time( 'mysql' ),
            'directives'   => $directives,
        ), false );

        // ── Auto-push gap keywords to SEO Sniper ──
        self::push_to_sniper( $recommendations );

        $total = array_sum( array_map( 'count', $directives ) );
        error_log( 'DBA TIS: Generated ' . $total . ' directives across ' . count( $directives ) . ' bots (including Kaizen).' );

        return $directives;
    }

    /**
     * Build a human-readable instruction for a bot or Kaizen.
     */
    private static function build_bot_instruction( $rec ) {
        $kws   = implode( ', ', array_slice( $rec['details']['keywords'] ?? array(), 0, 5 ) );
        $count = $rec['details']['pages_to_create'] ?? 3;

        switch ( $rec['type'] ) {
            case 'critical_gap':
                return "CRITICAL: Create {$count} new articles targeting: {$kws}. "
                     . "Current grade: {$rec['grade']}. This is a strategic priority. "
                     . "Each article should be 2000+ words, use target keywords in H1/H2, "
                     . "and include practical setup guides with step-by-step instructions.";

            case 'blind_spot':
                return "BLIND SPOT — ZERO PAGES EXIST: Create {$count} articles from scratch for: {$kws}. "
                     . "This topic has NO dedicated content. Start with a comprehensive pillar article, "
                     . "then create supporting articles covering setup, legal framework, taxation, "
                     . "and comparison with alternative structures.";

            case 'enhance':
            case 'enhance_and_generate':
                return "ENHANCE: Create {$count} new articles and optimize existing content for: {$kws}. "
                     . "Current grade: {$rec['grade']}. Focus on long-tail variations and "
                     . "comparison articles (e.g., 'RAIF vs SIF', 'SOPARFI vs SPF').";

            case 'seo_optimize':
                $fix_count = $rec['details']['pages_to_fix'] ?? 0;
                return "TITLE OPTIMIZATION: {$fix_count} pages cover \"{$rec['target']}\" but lack target keywords in their titles. "
                     . "Rewrite titles to include: {$kws}. "
                     . "Keep titles under 60 chars. Preserve the original topic focus.";

            case 'maintain':
                return "REFRESH: \"{$rec['target']}\" has Grade A coverage. "
                     . "Identify and refresh the 3 oldest articles: update statistics, legal references, "
                     . "and add current year context. Ensure target keywords appear in titles: {$kws}.";

            case 'rebalance':
                $pct = $rec['details']['percentage'] ?? 0;
                return "DEPRIORITISE: \"{$rec['target']}\" dominates at {$pct}% of all content. "
                     . "AVOID generating new articles on this topic until the percentage drops below 25%. "
                     . "Focus resources on strategic gaps instead.";

            default:
                return "Create content targeting: {$kws}";
        }
    }

    /**
     * Get active directives for a specific bot.
     * Called by generators during content creation.
     *
     * @param  string $bot_id  Bot identifier (e.g., 'luxstrat', 'geobot').
     * @return array           Array of directives for this bot, or empty.
     */
    public static function get_directives_for_bot( $bot_id ) {
        $data = get_option( self::DIRECTIVES_KEY, array() );
        $directives = $data['directives'] ?? array();
        return $directives[ $bot_id ] ?? array();
    }

    /**
     * Get the TIS context string to inject into a generator's system prompt.
     * Includes both CREATE priorities and DEPRIORITISE throttles.
     *
     * @param  string $bot_id  Bot identifier.
     * @return string          Prompt injection text (or empty).
     */
    public static function get_generator_context( $bot_id ) {
        $directives = self::get_directives_for_bot( $bot_id );
        if ( empty( $directives ) ) return '';

        $create_dirs      = array();
        $deprioritise_dirs = array();

        foreach ( $directives as $dir ) {
            $type = $dir['directive_type'] ?? 'create';
            if ( $type === 'deprioritise' ) {
                $deprioritise_dirs[] = $dir;
            } elseif ( in_array( $type, array( 'create', 'optimize_titles', 'refresh' ), true ) ) {
                $create_dirs[] = $dir;
            }
        }

        $context = "\n\n═══ TIS STRATEGIC PRIORITIES ═══\n";
        $context .= "The Topic Intelligence Scanner has identified the following content directives.\n\n";

        // ── CREATE / ENHANCE priorities ──
        if ( ! empty( $create_dirs ) ) {
            $context .= "PRIORITY TOPICS — When choosing subjects, STRONGLY PREFER these:\n\n";
            foreach ( $create_dirs as $idx => $dir ) {
                $urgency_icon = $dir['urgency'] === 'critical' ? '🔴' : ( $dir['urgency'] === 'high' ? '🟠' : '🟡' );
                $context .= ( $idx + 1 ) . ". {$urgency_icon} {$dir['target_label']} (Grade: {$dir['grade']})\n";
                $context .= "   Keywords to target: " . implode( ', ', array_slice( $dir['keywords'], 0, 5 ) ) . "\n";
                $context .= "   Instruction: {$dir['instruction']}\n\n";
            }
        }

        // ── DEPRIORITISE throttles ──
        if ( ! empty( $deprioritise_dirs ) ) {
            $context .= "⛔ TOPICS TO AVOID — Do NOT write about these (over-represented):\n\n";
            foreach ( $deprioritise_dirs as $dir ) {
                $context .= "  ✗ {$dir['target_label']} ({$dir['percentage']}% of all content) — {$dir['instruction']}\n";
            }
            $context .= "\n";
        }

        $context .= "Use these priorities to guide subject selection. Fill gaps first. Avoid over-covered topics.\n";
        $context .= "═══ END TIS PRIORITIES ═══\n";

        return $context;
    }

    /**
     * Mark a directive as completed (after content is generated).
     */
    public static function mark_directive_progress( $bot_id, $target_label, $pages_created = 1 ) {
        $data = get_option( self::DIRECTIVES_KEY, array() );
        if ( ! isset( $data['directives'][ $bot_id ] ) ) return;

        foreach ( $data['directives'][ $bot_id ] as &$dir ) {
            if ( $dir['target_label'] === $target_label ) {
                $dir['pages_to_create'] = max( 0, $dir['pages_to_create'] - $pages_created );
                if ( ! isset( $dir['pages_created'] ) ) $dir['pages_created'] = 0;
                $dir['pages_created'] += $pages_created;
                break;
            }
        }
        unset( $dir );

        update_option( self::DIRECTIVES_KEY, $data, false );
    }

    /**
     * Auto-detect which directive a newly created post fulfills based on title keywords.
     *
     * @param string $bot_id  Bot identifier (luxstrat, geobot, etc.)
     * @param string $title   The post title just created.
     */
    public static function auto_track_progress( $bot_id, $title ) {
        if ( empty( $title ) ) return;

        $data = get_option( self::DIRECTIVES_KEY, array() );
        if ( empty( $data['directives'] ) ) return;

        $title_lower = mb_strtolower( $title );

        // Check directives for this specific bot first, then fallback to all bots
        $bots_to_check = array();
        if ( isset( $data['directives'][ $bot_id ] ) ) {
            $bots_to_check[] = $bot_id;
        }
        // Also check generic directives assigned to any bot
        foreach ( array_keys( $data['directives'] ) as $bid ) {
            if ( $bid !== $bot_id ) $bots_to_check[] = $bid;
        }

        foreach ( $bots_to_check as $bid ) {
            if ( empty( $data['directives'][ $bid ] ) ) continue;
            foreach ( $data['directives'][ $bid ] as $dir ) {
                if ( empty( $dir['keywords'] ) ) continue;
                foreach ( $dir['keywords'] as $kw ) {
                    if ( mb_stripos( $title_lower, mb_strtolower( $kw ) ) !== false ) {
                        self::mark_directive_progress( $bid, $dir['target_label'] );
                        error_log( 'DBA TIS: Auto-tracked progress for "' . $dir['target_label'] . '" via bot ' . $bot_id . ' — title matched keyword "' . $kw . '"' );
                        return; // One match is enough
                    }
                }
            }
        }
    }

    /* ══════════════════════════════════════════════════════════════
     *  SUMMARY GENERATION
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Generate a human-readable executive summary of recommendations.
     */
    private static function generate_summary( $recs ) {
        $critical = count( array_filter( $recs, function( $r ) { return $r['priority'] === 'critical'; } ) );
        $high     = count( array_filter( $recs, function( $r ) { return $r['priority'] === 'high'; } ) );
        $medium   = count( array_filter( $recs, function( $r ) { return $r['priority'] === 'medium'; } ) );
        $maintain = count( array_filter( $recs, function( $r ) { return $r['type'] === 'maintain'; } ) );

        $total_pages_needed = 0;
        foreach ( $recs as $r ) {
            $total_pages_needed += $r['details']['pages_to_create'] ?? 0;
        }

        return array(
            'total_recommendations' => count( $recs ),
            'critical_gaps'         => $critical,
            'high_priority'         => $high,
            'medium_priority'       => $medium,
            'topics_on_track'       => $maintain,
            'total_pages_needed'    => $total_pages_needed,
            'headline'              => $critical > 0
                ? "⚠️ {$critical} critical content gaps detected — {$total_pages_needed} new pages recommended"
                : ( $high > 0
                    ? "📊 {$high} high-priority improvements identified"
                    : "✅ Content strategy is on track — {$maintain} topics well-covered" ),
        );
    }

    /* ══════════════════════════════════════════════════════════════
     *  KAIZEN CENTER INTEGRATION — Title fixes + content refresh
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Get Kaizen-specific directives (title optimization + refresh).
     * Called by Kaizen Center during batch processing.
     *
     * @return array  Array of Kaizen directives.
     */
    public static function get_kaizen_directives() {
        $data = get_option( self::DIRECTIVES_KEY, array() );
        return $data['directives']['kaizen'] ?? array();
    }

    /**
     * Get title optimization directives specifically.
     *
     * @return array  Directives with directive_type = 'optimize_titles'.
     */
    public static function get_title_fix_directives() {
        $kaizen = self::get_kaizen_directives();
        return array_filter( $kaizen, function( $d ) {
            return ( $d['directive_type'] ?? '' ) === 'optimize_titles';
        } );
    }

    /**
     * Get content refresh directives specifically.
     *
     * @return array  Directives with directive_type = 'refresh'.
     */
    public static function get_refresh_directives() {
        $kaizen = self::get_kaizen_directives();
        return array_filter( $kaizen, function( $d ) {
            return ( $d['directive_type'] ?? '' ) === 'refresh';
        } );
    }

    /* ══════════════════════════════════════════════════════════════
     *  SEO SNIPER INTEGRATION — Auto-push gap keywords
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Automatically push TIS gap keywords to SEO Sniper's queue.
     * Called after every directive generation cycle.
     *
     * Stores keywords in an option that SEO Sniper can consume.
     * This is the ACTIVE push — not waiting for Sniper to pull.
     *
     * @param  array $recommendations  Full recommendation list.
     */
    private static function push_to_sniper( $recommendations ) {
        $sniper_queue = array();

        foreach ( $recommendations as $rec ) {
            // Only push gap-related recommendations (things that need new content or fixing)
            if ( ! in_array( $rec['type'], array( 'critical_gap', 'blind_spot', 'enhance', 'enhance_and_generate', 'seo_optimize' ), true ) ) {
                continue;
            }

            foreach ( $rec['details']['keywords'] ?? array() as $kw ) {
                $sniper_queue[] = array(
                    'keyword'    => $kw,
                    'source'     => 'TIS: ' . $rec['target'],
                    'type'       => $rec['type'],
                    'priority'   => $rec['priority'],
                    'grade'      => $rec['grade'],
                    'target_bot' => $rec['details']['target_bot'] ?? 'luxstrat',
                    'pushed_at'  => current_time( 'mysql' ),
                );
            }
        }

        if ( ! empty( $sniper_queue ) ) {
            // Deduplicate by keyword + target_bot (same keyword for different bots is valid)
            $seen = array();
            $unique = array();
            foreach ( $sniper_queue as $item ) {
                $key = strtolower( $item['keyword'] ) . '||' . ( $item['target_bot'] ?? 'luxstrat' );
                if ( ! isset( $seen[ $key ] ) ) {
                    $seen[ $key ] = true;
                    $unique[] = $item;
                }
            }

            // Sort by priority
            $urgency_order = array( 'critical' => 0, 'high' => 1, 'medium' => 2, 'low' => 3 );
            usort( $unique, function( $a, $b ) use ( $urgency_order ) {
                return ( $urgency_order[ $a['priority'] ] ?? 4 ) <=> ( $urgency_order[ $b['priority'] ] ?? 4 );
            } );

            update_option( 'dba_tis_sniper_queue', array(
                'generated_at' => current_time( 'mysql' ),
                'keywords'     => $unique,
            ), false );

            error_log( 'DBA TIS → SEO Sniper: Pushed ' . count( $unique ) . ' keywords to sniper queue.' );
        }
    }

    /**
     * Get the active TIS→Sniper keyword queue.
     * Called by SEO Sniper admin to display suggested keywords.
     *
     * @return array  Array of keyword suggestions.
     */
    public static function get_sniper_queue() {
        $data = get_option( 'dba_tis_sniper_queue', array() );
        return $data['keywords'] ?? array();
    }

    /**
     * Get suggested keywords for SEO Sniper based on TIS gaps.
     */
    public static function get_sniper_suggestions() {
        $recs = get_option( self::RECS_KEY, array() );
        $all_recs = $recs['recommendations'] ?? array();
        $suggestions = array();

        foreach ( $all_recs as $rec ) {
            if ( ! in_array( $rec['type'], array( 'critical_gap', 'enhance', 'enhance_and_generate' ) ) ) continue;

            foreach ( $rec['details']['keywords'] ?? array() as $kw ) {
                $suggestions[] = array(
                    'keyword'  => $kw,
                    'source'   => 'TIS: ' . $rec['target'],
                    'priority' => $rec['priority'],
                    'grade'    => $rec['grade'],
                );
            }
        }

        return $suggestions;
    }
}
