<?php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * AI Service — Routes generation to the active AI provider or falls back to curated English content.
 */
class SBPAI_Service_AI {

    /** All supported providers */
    public static function get_providers(): array {
        return [
            // --- Free / Open-access ---
            'groq'        => [ 'label' => 'Groq (Free)',           'url' => 'https://api.groq.com/openai/v1/chat/completions',          'model' => 'llama3-70b-8192',              'free' => true  ],
            'gemini'      => [ 'label' => 'Google Gemini',         'url' => 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent', 'model' => 'gemini-2.0-flash', 'free' => true  ],
            'huggingface' => [ 'label' => 'Hugging Face (Free)',    'url' => 'https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3', 'model' => '', 'free' => true ],
            'mistral'     => [ 'label' => 'Mistral AI (Free tier)', 'url' => 'https://api.mistral.ai/v1/chat/completions',               'model' => 'mistral-small-latest',         'free' => true  ],
            'cohere'      => [ 'label' => 'Cohere (Trial)',         'url' => 'https://api.cohere.ai/v1/generate',                        'model' => 'command',                      'free' => true  ],
            // --- Paid ---
            'openai'      => [ 'label' => 'OpenAI (Paid)',          'url' => 'https://api.openai.com/v1/chat/completions',               'model' => 'gpt-4o-mini',                  'free' => false ],
            'claude'      => [ 'label' => 'Anthropic Claude (Paid)','url' => 'https://api.anthropic.com/v1/messages',                   'model' => 'claude-3-haiku-20240307',      'free' => false ],
            'openrouter'  => [ 'label' => 'OpenRouter (Mixed)',     'url' => 'https://openrouter.ai/api/v1/chat/completions',            'model' => 'mistralai/mistral-7b-instruct','free' => false ],
            'together'    => [ 'label' => 'Together AI (Paid)',     'url' => 'https://api.together.xyz/v1/chat/completions',             'model' => 'meta-llama/Llama-3-8b-chat-hf','free' => false ],
            'perplexity'  => [ 'label' => 'Perplexity (Paid)',      'url' => 'https://api.perplexity.ai/chat/completions',              'model' => 'llama-3-sonar-small-32k-chat', 'free' => false ],
        ];
    }

    // ─── Niche Content Library ──────────────────────────────────────────────

    /**
     * Returns curated English title templates per niche.
     *
     * @param  string $niche  Active niche slug.
     * @param  string $type   Post type context (post, page, product …).
     * @return string[]
     */
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
    public static function get_niche_titles( string $niche, string $type = 'post' ): array {
        $library = [
            'Fashion' => [
                'post' => [
                    '10 Must-Have Fashion Trends This Season',
                    'How to Build a Capsule Wardrobe on a Budget',
                    'The Ultimate Guide to Sustainable Fashion',
                    'Street Style Inspiration: Looks We Love',
                    'How to Style a Little Black Dress for Every Occasion',
                    'Top 5 Designer Bags Worth the Investment',
                    'The Return of Vintage Denim: What You Need to Know',
                    'How to Dress for Your Body Type with Confidence',
                    'Spring/Summer Colour Palettes Every Stylist Recommends',
                    'The Science Behind Why We Love Certain Fabrics',
                    'Celebrity Fashion Moments That Defined the Decade',
                    'Minimalist Fashion: Less is Truly More',
                ],
                'page' => [
                    'Our Story',
                    'Style Guide',
                    'Lookbook',
                    'Brand Values',
                    'Sustainability Commitment',
                    'Care Instructions',
                ],
            ],
            'Technology' => [
                'post' => [
                    'The Future of Artificial Intelligence in Everyday Life',
                    '10 Open-Source Tools Every Developer Should Know',
                    'How Quantum Computing Will Change Cybersecurity',
                    'Building Your First REST API: A Beginners Guide',
                    'The Rise of Edge Computing and What It Means for You',
                    'Cloud vs On-Premise: Which Architecture Fits Your Business',
                    'Understanding Large Language Models in Plain English',
                    'How to Secure Your Home Network in 2025',
                    'Best Practices for Writing Clean, Maintainable Code',
                    'Web Performance Optimization: A Complete Checklist',
                    'Microservices vs Monolith: Pros, Cons, and Trade-offs',
                    'Getting Started with Kubernetes for Backend Engineers',
                ],
                'page' => [
                    'About Us',
                    'Our Technology Stack',
                    'Engineering Blog',
                    'Open Source Projects',
                    'Privacy Policy',
                    'API Documentation',
                ],
            ],
            'Real Estate' => [
                'post' => [
                    '5 Things to Check Before Buying Your First Home',
                    'How to Stage Your Home for a Faster Sale',
                    'Understanding Mortgage Rates in a High-Interest Environment',
                    'The Best Neighbourhoods to Invest in Right Now',
                    'Renting vs Buying: A Financial Breakdown',
                    'Commercial Real Estate Trends to Watch This Year',
                    'How to Negotiate the Best Price When Buying a Home',
                    'Interior Design Ideas That Increase Property Value',
                    'A Guide to Real Estate Investment Trusts (REITs)',
                    'How Smart Home Technology Affects Property Prices',
                    'First-Time Buyer Grants and Incentives Explained',
                    'The Role of a Real Estate Agent: What You\'re Actually Paying For',
                ],
                'page' => [
                    'About Our Agency',
                    'Properties for Sale',
                    'Featured Listings',
                    'Sell Your Property',
                    'Mortgage Calculator',
                    'Contact an Agent',
                ],
            ],
            'Fitness' => [
                'post' => [
                    'The Best Full-Body Workout You Can Do at Home',
                    'How to Break Through a Fitness Plateau',
                    'Nutrition Myths Debunked by Sports Scientists',
                    '30-Day Strength Training Plan for Beginners',
                    'The Science Behind HIIT and Why It Works',
                    'How Mental Health and Physical Fitness Are Connected',
                    'Building a Morning Routine That Actually Sticks',
                    'The Truth About Protein Supplements: Do You Really Need Them?',
                    'Yoga for Athletes: Improving Flexibility and Recovery',
                    'How to Train for Your First 5K Run',
                    'The Best Pre- and Post-Workout Meals',
                    'Sleep, Recovery, and Peak Athletic Performance',
                ],
                'page' => [
                    'Our Fitness Philosophy',
                    'Class Schedule',
                    'Personal Training',
                    'Member Success Stories',
                    'Nutrition Guide',
                    'Book a Session',
                ],
            ],
            'E-commerce' => [
                'post' => [
                    'How to Write Product Descriptions That Actually Convert',
                    'Cart Abandonment: 7 Proven Strategies to Win Customers Back',
                    'The Complete Guide to Setting Up Google Shopping Ads',
                    'Email Marketing Sequences That Drive Repeat Purchases',
                    'How to Choose the Right Shipping Strategy for Your Store',
                    'Understanding Customer Lifetime Value (CLV)',
                    'A/B Testing Your Product Pages: Where to Start',
                    'How to Handle Returns and Refunds Without Losing Customers',
                    'The Rise of Social Commerce and How to Leverage It',
                    'SEO for E-commerce: Ranking Your Category Pages',
                    'Building Trust with First-Time Buyers',
                    'How to Price Your Products for Maximum Profit',
                ],
                'page' => [
                    'About Our Store',
                    'Shipping & Returns',
                    'FAQ',
                    'Customer Reviews',
                    'Wholesale Enquiries',
                    'Track Your Order',
                ],
            ],
            'Health' => [
                'post' => [
                    'The Mediterranean Diet: A Complete Evidence-Based Guide',
                    'How to Lower Your Blood Pressure Naturally',
                    '10 Warning Signs You Should Never Ignore',
                    'Understanding Type 2 Diabetes: Prevention and Management',
                    'The Mental Health Benefits of Spending Time in Nature',
                    'Sleep Hygiene: How to Get 7-9 Hours of Quality Rest',
                    'How Gut Microbiome Affects Your Immune System',
                    'The Dangers of Sitting All Day and How to Combat Them',
                    'Mindfulness Meditation: A Beginners Guide with Exercises',
                    'Vitamins and Minerals: What Most People Are Deficient In',
                    'How to Talk to Your Doctor About Mental Health',
                    'Managing Chronic Pain: Integrative Approaches That Help',
                ],
                'page' => [
                    'About Our Clinic',
                    'Services',
                    'Meet the Team',
                    'Patient Resources',
                    'Book an Appointment',
                    'Insurance Plans Accepted',
                ],
            ],
            'Food' => [
                'post' => [
                    '15-Minute Weeknight Meals That Taste Like You Spent Hours',
                    'The Secret to Perfect Homemade Pasta Every Time',
                    'Meal Prep Sunday: A Full Week of Lunches Under £20',
                    'How to Season Cast Iron and Why It Matters',
                    'Classic French Sauces Every Home Cook Should Master',
                    'Fermentation 101: How to Make Your Own Kimchi',
                    'The Best Street Foods Around the World',
                    'Baking Bread at Home: The Definitive Beginner\'s Guide',
                    'How to Build a Balanced Plant-Based Meal Plan',
                    'Chocolate Desserts Ranked from Easiest to Most Impressive',
                    'Why Mise en Place Is the Chef\'s Secret Weapon',
                    'Wine Pairing Guide: What Goes with What',
                ],
                'page' => [
                    'Our Restaurant Story',
                    'Menu',
                    'Reservations',
                    'Private Dining',
                    'Chef\'s Table Experience',
                    'Food Allergy Information',
                ],
            ],
            'Travel' => [
                'post' => [
                    '10 Hidden Gems in Europe You Haven\'t Heard Of Yet',
                    'How to Travel Solo for the First Time: Practical Advice',
                    'The Best Budget Airlines and When to Book',
                    'A First-Timer\'s Guide to Southeast Asia',
                    'How to Pack Light for a Two-Week Trip',
                    'The World\'s Most Scenic Train Journeys',
                    'Digital Nomad Life: The Reality Behind the Instagram Posts',
                    'Responsible Tourism: How to Travel Without Harming Communities',
                    'How to Get Cheap Flights Using Google Flights and Alerts',
                    'Must-Visit National Parks in North America',
                    'Travelling with Kids: Survival Tips from Real Parents',
                    'The Best Time of Year to Visit Every Continent',
                ],
                'page' => [
                    'About Our Travel Agency',
                    'Featured Destinations',
                    'Group Tours',
                    'Custom Itineraries',
                    'Travel Insurance',
                    'Visa Assistance',
                ],
            ],
            'Finance' => [
                'post' => [
                    'How to Build an Emergency Fund from Scratch',
                    'Index Funds vs Actively Managed Funds: Which Wins?',
                    'The 50/30/20 Budget Rule: Does It Actually Work?',
                    'How to Invest in Your 20s and Set Yourself Up for Life',
                    'Understanding Your Credit Score and How to Improve It',
                    'Passive Income Strategies That Actually Generate Money',
                    'The Basics of Tax-Efficient Investing',
                    'Cryptocurrency: What Every Beginner Needs to Know',
                    'How to Pay Off Student Loans Faster',
                    'Retirement Planning: Starting at 30, 40, and 50',
                    'How Inflation Erodes Savings and What to Do About It',
                    'The Best High-Yield Savings Accounts Right Now',
                ],
                'page' => [
                    'About Our Advisory Firm',
                    'Financial Planning Services',
                    'Investment Portfolio Review',
                    'Client Success Stories',
                    'Fee Structure',
                    'Book a Free Consultation',
                ],
            ],
        ];

        $niche_data = $library[ $niche ] ?? null;
        if ( $niche_data ) {
            return $niche_data[ $type ] ?? $niche_data['post'] ?? [];
        }
        // General fallback
        return [
            'Getting Started: A Comprehensive Beginner\'s Guide',
            'The Top 10 Things You Need to Know About This Topic',
            'How to Master This Subject in 30 Days',
            'Common Mistakes Everyone Makes and How to Avoid Them',
            'The Ultimate Resource Guide for Beginners and Experts Alike',
            'A Step-by-Step Approach to Solving This Problem',
            'Why This Matters More Than You Think',
            'Frequently Asked Questions: Everything You Need to Know',
            'A Deep Dive Into the Most Important Concepts',
            'What the Experts Say vs What the Data Shows',
        ];
    }

    /**
     * Returns curated English paragraph templates per niche.
     *
     * @param  string $niche  Active niche slug.
     * @param  string $title  Title to weave into the content.
     * @param  int    $count  Number of paragraphs desired.
     * @return string
     */
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
    public static function get_niche_content( string $niche, string $title, int $count = 4 ): string {
        $intros = [
            'Fashion'     => "In the ever-evolving world of fashion, staying ahead of the curve is both an art and a science. \"{$title}\" explores the forces shaping what we wear and why it matters.",
            'Technology'  => "Technology continues to reshape every aspect of modern life at a breathtaking pace. In this article, we explore \"{$title}\" and what it means for developers, businesses, and everyday users.",
            'Real Estate' => "The property market is in constant flux, driven by interest rates, demographics, and shifting lifestyle priorities. \"{$title}\" cuts through the noise to give you actionable insights.",
            'Fitness'     => "Achieving and maintaining peak physical fitness requires more than motivation — it demands strategy and consistency. \"{$title}\" gives you the evidence-based roadmap you need.",
            'E-commerce'  => "Running a successful online store demands continuous optimisation and a deep understanding of customer behaviour. \"{$title}\" breaks down what the top performers are doing differently.",
            'Health'      => "Your health is your most valuable asset, and understanding how to protect it has never been more important. \"{$title}\" draws on the latest research to give you practical guidance.",
            'Food'        => "Food is culture, nourishment, and pleasure all rolled into one extraordinary experience. \"{$title}\" invites you into the kitchen and beyond to discover something delicious.",
            'Travel'      => "Travel broadens the mind, challenges assumptions, and creates memories that last a lifetime. \"{$title}\" is your compass for the journey ahead.",
            'Finance'     => "Financial literacy is one of the most powerful skills you can develop, yet most people never receive a proper financial education. \"{$title}\" changes that.",
        ];

        $bodies = [
            'Fashion'     => [
                "Understanding fashion trends requires looking beyond the runway. Designers draw inspiration from art, politics, and social movements to create collections that resonate with specific cultural moments. This season, the focus has shifted toward versatility and longevity over fast-fashion disposability.",
                "Building a sustainable wardrobe doesn't mean sacrificing style. It means investing in quality pieces that transcend seasonal trends — classic cuts, natural materials, and timeless colour palettes that work across a variety of occasions and settings.",
                "Personal style is ultimately a form of self-expression. The most fashionable people aren't necessarily those following trends blindly; they're the ones who understand their own aesthetic and dress with intention and confidence.",
                "The fashion industry is one of the largest polluters in the world, which is why the shift toward circular fashion, deadstock fabrics, and transparent supply chains is so significant. Consumers are increasingly voting with their wallets for brands that align with their values.",
                "Accessories remain the quickest and most affordable way to update any outfit. A statement bag, a pair of bold earrings, or the right footwear can transform a basic look into something memorable without requiring a complete wardrobe overhaul.",
            ],
            'Technology'  => [
                "Modern software development has moved far beyond the lone programmer writing code in isolation. Today's engineering teams work in tightly integrated cross-functional units, deploying code dozens of times per day using CI/CD pipelines and automated testing frameworks.",
                "Artificial intelligence is no longer a future technology — it's embedded in the tools we use every day, from email filters and navigation apps to medical diagnostics and financial modelling. Understanding the basics of how these systems work is increasingly essential for professionals in every field.",
                "Security remains the most critical and often underinvested aspect of software systems. With the average cost of a data breach exceeding $4 million, organisations that treat security as an afterthought rather than a foundational design principle are taking significant financial and reputational risks.",
                "Open-source software has become the backbone of the modern internet. Projects like Linux, Kubernetes, PostgreSQL, and React are maintained by global communities of contributors and power the infrastructure of some of the world's most valuable companies.",
                "Performance optimisation is both a technical discipline and a user experience imperative. Studies consistently show that a one-second delay in page load time can reduce conversions by up to 7%, making the business case for well-optimised systems irrefutable.",
            ],
            'Real Estate' => [
                "Location has always been the primary driver of property value, but the definition of a desirable location is changing. Proximity to major employment hubs remains important, but quality of local schools, green space, and community amenities are increasingly influencing buyer decisions.",
                "Understanding mortgage products is essential for any first-time buyer. Fixed-rate mortgages offer payment certainty, while variable-rate products can be advantageous in a falling interest rate environment. Speaking to an independent broker rather than going directly to a bank almost always results in better terms.",
                "Property investment requires a long-term mindset. Short-term market fluctuations are inevitable, but residential property in well-chosen locations has historically delivered consistent capital appreciation over decade-long holding periods.",
                "Staging a property for sale is one of the highest-return investments a vendor can make. Research consistently shows that professionally staged homes sell faster and for more money — often recouping ten times the cost of the staging in additional sale price.",
                "Due diligence before purchasing any property should include a full structural survey, review of planning permissions and building regulations compliance, investigation of any flood risk or environmental concerns, and a thorough check of the title register.",
            ],
            'Fitness'     => [
                "Progressive overload — gradually increasing the weight, frequency, or intensity of your training — is the fundamental principle underpinning all strength and hypertrophy training. Without it, your body has no biological reason to adapt and grow stronger.",
                "Nutrition accounts for at least 70% of body composition outcomes. No amount of training can out-exercise a consistently poor diet, which is why focusing on protein intake, calorie balance, and food quality before optimising your workout programme is the logical starting point.",
                "Recovery is where the real gains happen. Sleep is the body's primary repair mechanism, and training intensity beyond your recovery capacity leads not to improvement but to overtraining syndrome — a state of persistent fatigue, declining performance, and elevated injury risk.",
                "Cardiovascular fitness and strength training are not mutually exclusive — in fact, the evidence is clear that combining both produces superior health outcomes compared to focusing on either in isolation. The key is appropriate programming that prevents interference effects.",
                "Consistency over intensity is the mantra of every successful long-term athlete. A moderate, sustainable programme followed every week for two years will always produce better results than an aggressive programme abandoned within a month.",
            ],
            'E-commerce'  => [
                "Product photography is one of the highest-leverage investments an e-commerce brand can make. Research shows that professional product images can increase conversion rates by up to 30%, while poor-quality imagery is cited by over 60% of shoppers as a reason not to purchase.",
                "Email marketing continues to deliver the highest ROI of any digital marketing channel — approximately $42 for every $1 spent, according to industry data. A well-structured welcome sequence, post-purchase flow, and re-engagement campaign are the foundation of every successful e-commerce email programme.",
                "Customer reviews are the modern equivalent of word-of-mouth recommendations. Displaying authentic UGC (user-generated content) and verified reviews prominently on product pages significantly reduces purchase hesitation, particularly among first-time buyers who haven't yet built trust with your brand.",
                "Free shipping has effectively become the expected standard in e-commerce. Brands that charge for shipping without offering a compelling reason see significantly higher cart abandonment rates. The cost of shipping can be absorbed into product pricing or used as an incentive tied to minimum order values.",
                "Retention is more profitable than acquisition. Acquiring a new customer costs five times more than retaining an existing one, yet most e-commerce businesses spend the majority of their marketing budget on acquisition. Loyalty programmes, personalised restock reminders, and VIP tiers dramatically improve LTV.",
            ],
            'Health'      => [
                "Preventive healthcare is far more cost-effective than treating established disease. Regular screening, vaccination, healthy dietary patterns, and adequate physical activity can prevent or delay the onset of the most prevalent chronic conditions, including cardiovascular disease, type 2 diabetes, and certain cancers.",
                "Mental health is inseparable from physical health. Chronic stress elevates cortisol levels, suppresses immune function, disrupts sleep architecture, and increases cardiovascular risk. Addressing psychological wellbeing is therefore as medically important as managing blood pressure or cholesterol.",
                "Sleep is the most underrated pillar of health. During deep sleep, the brain clears metabolic waste products including amyloid plaques associated with Alzheimer's disease, muscles repair, and hormonal balance is restored. Adults consistently sleeping fewer than 6 hours per night face dramatically elevated health risks.",
                "The gut microbiome has emerged as one of the most exciting frontiers in medical research. The trillions of bacteria living in your digestive tract influence not just digestion and immune function, but also mood, cognitive function, and even cardiovascular health through complex bidirectional signalling pathways.",
                "Evidence-based medicine means treatments backed by rigorous clinical trial data, not anecdote or commercial interest. When evaluating health claims — particularly from supplement companies and wellness influencers — looking for peer-reviewed meta-analyses rather than single studies or testimonials is essential.",
            ],
            'Food'        => [
                "The foundation of great cooking is understanding flavour. The five basic tastes — sweet, salty, sour, bitter, and umami — interact in predictable ways, and skilled cooks manipulate their balance intuitively. Salt doesn't just make food salty; it suppresses bitterness and amplifies every other flavour present.",
                "Mise en place — the French culinary term for 'everything in its place' — is the practice of preparing and organising all ingredients before cooking begins. This discipline, borrowed from professional kitchens, reduces stress, prevents mistakes, and allows you to focus entirely on technique during the actual cooking process.",
                "Knife skills are the single most impactful technical skill a home cook can develop. A sharp, well-maintained knife and confident cutting technique dramatically reduce prep time, improve consistency of cooking (uniformly-sized pieces cook at the same rate), and significantly reduce the risk of injury compared to struggling with blunt blades.",
                "Umami — the fifth taste discovered by Japanese chemist Kikunae Ikeda in 1908 — is the savoury depth found in ingredients like parmesan, miso, soy sauce, tomatoes, and mushrooms. Understanding how to layer umami sources is the key to making quick weeknight meals taste complex and satisfying.",
                "Fermentation is one of humanity's oldest and most nutritionally significant food preparation techniques. Fermented foods like yoghurt, kimchi, sauerkraut, and sourdough bread are rich in probiotic bacteria and beneficial acids, and their regular consumption is associated with improved gut health and immune function.",
            ],
            'Travel'      => [
                "The best travel experiences almost never appear in glossy brochures. They're the unplanned conversations with locals, the back-street restaurants with no English menus, and the mistaken turns that lead to the most memorable views. Building flexibility into your itinerary is the difference between touring and genuinely travelling.",
                "Budget travel is a skill that improves with practice. The fundamentals — travelling in shoulder seasons, using flight comparison tools effectively, choosing accommodation that reflects genuine priorities rather than status, and eating where the locals eat — can reduce the cost of a trip by 40-60% without compromising the quality of the experience.",
                "Responsible tourism begins before you board a plane. Researching your destination's cultural norms, economic pressures, and environmental sensitivities allows you to make choices that support local communities rather than inadvertently extracting value from them. Small decisions — where you eat, what you buy, who guides you — collectively matter enormously.",
                "Solo travel remains one of the most personally transformative experiences available. Without the social cushion of companions, you're compelled to initiate conversations, make independent decisions, and confront your own capability and resilience. Most solo travellers report that the fear preceding the first solo trip was vastly disproportionate to the reality.",
                "Packing light is a skill with compounding returns. Every kilogram you don't carry translates to faster airport transitions, the ability to use public transport rather than taxis, and dramatically reduced physical strain across long travel days. The universal packing advice of experienced travellers is always the same: pack what you think you need, then leave half of it behind.",
            ],
            'Finance'     => [
                "Compound interest is the most powerful force in personal finance — and it works both for and against you. Invested early and left untouched, modest sums grow into significant wealth over decades. Applied to debt, the same principle silently accumulates financial obligations that can take years to escape.",
                "Diversification is the only free lunch in investing. By spreading capital across asset classes, geographies, and sectors that don't move in perfect correlation, investors can achieve a given level of return at significantly lower risk than concentrating in any single position.",
                "Emergency funds are the foundation of financial security before any investment activity begins. Three to six months of essential living expenses held in an instantly accessible, low-risk account provides the buffer that prevents temporary income shocks from becoming permanent financial setbacks.",
                "Tax efficiency is one of the most reliably impactful — and most consistently overlooked — aspects of long-term wealth building. Utilising available tax-advantaged accounts (ISAs, SIPPs, 401k, Roth IRA) before investing in taxable accounts can make a difference of tens of thousands over a working lifetime.",
                "Behavioural finance research consistently demonstrates that the average retail investor significantly underperforms index funds — not due to intelligence or information disadvantage, but because of emotional decision-making. Buying after markets rise and panic-selling during corrections is the single most costly mistake private investors make.",
            ],
        ];

        $niche_intros = $intros[ $niche ] ?? "This comprehensive guide covers everything you need to know about \"{$title}\", providing clear, actionable insights you can apply immediately.";
        $niche_bodies = $bodies[ $niche ] ?? [
            "Understanding the fundamentals is the essential first step. Without a solid grounding in the core principles, it's easy to get lost in complexity or make avoidable mistakes that set progress back significantly.",
            "Practical application is where knowledge becomes skill. The concepts explored here are not merely theoretical — they're drawn from real-world experience and designed to be applied directly to your specific situation.",
            "Common mistakes in this area often stem from rushing the process or skipping foundational steps. Taking the time to build a proper framework before optimising for efficiency almost always produces better long-term outcomes.",
            "The most successful practitioners share one trait above all others: consistency. Regular, disciplined practice of the core principles outperforms sporadic bursts of intense effort virtually every time.",
            "Staying informed is a continuous responsibility. Developments in this field happen rapidly, and those who commit to lifelong learning consistently outperform those who rely on knowledge acquired years or decades ago.",
        ];

        // Shuffle body paragraphs and pick $count of them
        shuffle( $niche_bodies );
        $selected = array_slice( $niche_bodies, 0, min( $count, count( $niche_bodies ) ) );

        $parts = [ $niche_intros ];
        foreach ( $selected as $para ) {
            $parts[] = $para;
        }

        return implode( "\n\n", $parts );
    }

    // ─── Core Generation Methods ────────────────────────────────────────────

    /**
     * Generate a contextually coherent title + body pair.
     * Returns ['title' => string, 'content' => string].
     *
     * @param  string $post_type  WordPress post type context.
     * @param  string $source     'ai', 'faker', or 'hybrid'.
     * @param  string $directive  Length/tone directive for the AI prompt.
     * @param  int    $p_count    Number of paragraphs for Faker fallback.
     * @return array{title: string, content: string}
     */
    public static function generate_title_and_content( string $post_type = 'post', string $source = 'hybrid', string $directive = '', int $p_count = 4 ): array {
        $niche = get_option( 'sbpai_active_niche', 'General' );

        // ── AI path ─────────────────────────────────────────────────────────
        if ( $source === 'ai' || $source === 'hybrid' ) {
            $use_ai           = (bool) get_option( 'sbpai_use_ai_provider', 0 );
            $primary_provider = get_option( 'sbpai_ai_provider', '' );
            $primary_key      = get_option( 'sbpai_ai_api_key_' . $primary_provider, '' );
            $fallback_provider = get_option( 'sbpai_ai_fallback_provider', '' );
            $fallback_key      = get_option( 'sbpai_ai_api_key_fallback_' . $fallback_provider, '' );

            if ( $use_ai && $primary_provider && $primary_key ) {
                $niche_ctx     = ( $niche && $niche !== 'General' ) ? "You are a professional content writer specialising in {$niche}. " : '';
                $title_prompt  = $niche_ctx . "Write ONE compelling, specific {$post_type} title for a {$niche} website. Return ONLY the title text, nothing else, no quotes, no explanation.";

                // Generate title
                $ai_title = null;
                $ai_title = self::call_provider( $primary_provider, $primary_key, $title_prompt );
                if ( ! $ai_title && $fallback_provider && $fallback_key && $fallback_provider !== $primary_provider ) {
                    $ai_title = self::call_provider( $fallback_provider, $fallback_key, $title_prompt );
                }

                // Generate content using the title as context
                if ( $ai_title ) {
                    $ai_title       = self::clean_title( trim( $ai_title ) );
                    $content_prompt = $niche_ctx . "Write an engaging, well-structured {$post_type} article titled \"{$ai_title}\". {$directive} Write in clear, professional English. Return only the article body paragraphs, no title heading, no markdown code fences.";
                    $ai_content     = self::call_provider( $primary_provider, $primary_key, $content_prompt );
                    if ( ! $ai_content && $fallback_provider && $fallback_key && $fallback_provider !== $primary_provider ) {
                        $ai_content = self::call_provider( $fallback_provider, $fallback_key, $content_prompt );
                    }
                    if ( $ai_content ) {
                        return [
                            'title'   => $ai_title,
                            'content' => trim( $ai_content ),
                        ];
                    }
                    // AI title OK but content failed — use niche content for body
                    return [
                        'title'   => $ai_title,
                        'content' => self::get_niche_content( $niche, $ai_title, $p_count ),
                    ];
                }
            }
        }

        // ── Curated English Faker fallback ───────────────────────────────────
        $titles = self::get_niche_titles( $niche, $post_type );
        if ( empty( $titles ) ) {
            $titles = self::get_niche_titles( 'General', $post_type );
        }
        shuffle( $titles );
        $title   = $titles[0];
        $content = self::get_niche_content( $niche, $title, $p_count );

        return [
            'title'   => $title,
            'content' => $content,
        ];
    }

    /**
     * Legacy single-text generation — kept for backward compatibility.
     */
    public static function generate_text( string $prompt, string $context = 'general' ): string {
        $niche            = get_option( 'sbpai_active_niche', 'General' );
        $use_ai           = (bool) get_option( 'sbpai_use_ai_provider', 0 );
        $primary_provider = get_option( 'sbpai_ai_provider', '' );
        $primary_key      = get_option( 'sbpai_ai_api_key_' . $primary_provider, '' );
        $fallback_provider = get_option( 'sbpai_ai_fallback_provider', '' );
        $fallback_key      = get_option( 'sbpai_ai_api_key_fallback_' . $fallback_provider, '' );

        if ( $use_ai ) {
            $niche_prefix = ( $niche && $niche !== 'General' ) ? "You are a content writer for a {$niche} website. " : '';
            $full_prompt  = $niche_prefix . $prompt;

            if ( $primary_provider && $primary_key ) {
                $result = self::call_provider( $primary_provider, $primary_key, $full_prompt );
                if ( $result ) return trim( $result );
            }
            if ( $fallback_provider && $fallback_key && $fallback_provider !== $primary_provider ) {
                $result = self::call_provider( $fallback_provider, $fallback_key, $full_prompt );
                if ( $result ) return trim( $result );
            }
        }

        // Curated English fallback
        if ( stripos( $prompt, 'title' ) !== false || stripos( $prompt, 'name' ) !== false ) {
            $titles = self::get_niche_titles( $niche );
            shuffle( $titles );
            return $titles[0];
        }
        $title = self::get_niche_titles( $niche )[0] ?? 'General Topic';
        return self::get_niche_content( $niche, $title );
    }

    // ─── Private Helpers ─────────────────────────────────────────────────────

    /**
     * Remove common AI artifacts from generated titles.
     */
    private static function clean_title( string $title ): string {
        // Strip surrounding quotes
        $title = trim( $title, '"\'`' );
        // Remove "Title:" prefix that some models return
        $title = preg_replace( '/^(title\s*:?\s*)/i', '', $title );
        // Remove markdown bold/italic markers
        $title = str_replace( [ '**', '__', '*', '_' ], '', $title );
        // Strip any newlines — keep only the first line
        $parts = explode( "\n", $title );
        return trim( $parts[0] );
    }

    // ─── Provider Dispatch ────────────────────────────────────────────────────

    /** Dispatch to the correct provider API. */
    public static function call_provider( string $provider, string $api_key, string $prompt ): ?string {
        $providers = self::get_providers();
        if ( ! isset( $providers[ $provider ] ) ) return null;
        $cfg = $providers[ $provider ];

        switch ( $provider ) {
            case 'gemini':      return self::_call_gemini( $api_key, $prompt, $cfg );
            case 'claude':      return self::_call_claude( $api_key, $prompt, $cfg );
            case 'cohere':      return self::_call_cohere( $api_key, $prompt, $cfg );
            case 'huggingface': return self::_call_huggingface( $api_key, $prompt, $cfg );
            default:            return self::_call_openai_compat( $api_key, $prompt, $cfg );
        }
    }

    /** OpenAI-compatible chat endpoint */
    private static function _call_openai_compat( string $key, string $prompt, array $cfg ): ?string {
        $response = wp_remote_post( $cfg['url'], [
            'timeout' => 25,
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'body' => wp_json_encode( [
                'model'       => $cfg['model'],
                'messages'    => [ [ 'role' => 'user', 'content' => $prompt ] ],
                'max_tokens'  => 800,
                'temperature' => 0.7,
            ] ),
        ] );
        if ( is_wp_error( $response ) ) return null;
        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        return $data['choices'][0]['message']['content'] ?? null;
    }

    /** Google Gemini */
    private static function _call_gemini( string $key, string $prompt, array $cfg ): ?string {
        $url  = $cfg['url'] . '?key=' . $key;
        $response = wp_remote_post( $url, [
            'timeout' => 25,
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => wp_json_encode( [
                'contents' => [ [ 'parts' => [ [ 'text' => $prompt ] ] ] ],
                'generationConfig' => [ 'maxOutputTokens' => 800, 'temperature' => 0.7 ],
            ] ),
        ] );
        if ( is_wp_error( $response ) ) return null;
        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        return $data['candidates'][0]['content']['parts'][0]['text'] ?? null;
    }

    /** Anthropic Claude */
    private static function _call_claude( string $key, string $prompt, array $cfg ): ?string {
        $response = wp_remote_post( $cfg['url'], [
            'timeout' => 25,
            'headers' => [
                'x-api-key'         => $key,
                'anthropic-version' => '2023-06-01',
                'Content-Type'      => 'application/json',
            ],
            'body' => wp_json_encode( [
                'model'      => $cfg['model'],
                'max_tokens' => 800,
                'messages'   => [ [ 'role' => 'user', 'content' => $prompt ] ],
            ] ),
        ] );
        if ( is_wp_error( $response ) ) return null;
        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        return $data['content'][0]['text'] ?? null;
    }

    /** Cohere */
    private static function _call_cohere( string $key, string $prompt, array $cfg ): ?string {
        $response = wp_remote_post( $cfg['url'], [
            'timeout' => 25,
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'body' => wp_json_encode( [ 'model' => $cfg['model'], 'prompt' => $prompt, 'max_tokens' => 800 ] ),
        ] );
        if ( is_wp_error( $response ) ) return null;
        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        return $data['generations'][0]['text'] ?? null;
    }

    /** Hugging Face Inference API */
    private static function _call_huggingface( string $key, string $prompt, array $cfg ): ?string {
        $response = wp_remote_post( $cfg['url'], [
            'timeout' => 30,
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'body' => wp_json_encode( [ 'inputs' => $prompt, 'parameters' => [ 'max_new_tokens' => 600 ] ] ),
        ] );
        if ( is_wp_error( $response ) ) return null;
        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( is_array( $data ) && isset( $data[0]['generated_text'] ) ) {
            return str_replace( $prompt, '', $data[0]['generated_text'] );
        }
        return null;
    }

    /**
     * Test connection — calls the provider with a minimal prompt.
     *
     * @return array{success: bool, message: string}
     */
    public static function test_connection( string $provider, string $api_key ): array {
        $result = self::call_provider( $provider, $api_key, 'Say "OK" in one word.' );
        if ( $result ) {
            return [ 'success' => true,  'message' => 'Connection successful! Response: ' . substr( $result, 0, 80 ) ];
        }
        return [ 'success' => false, 'message' => 'Connection failed. Check your API key and network.' ];
    }
}
