<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * API Handler for Gemini and Pexels
 */
class Trendly_AI_Post_API_Handler {
    private $gemini_key;
    private $pexels_key;

    public function __construct() {
        $opts = get_option( 'trendly_ai_post_options', [] );
        $this->gemini_key = $opts['gemini_api_key'] ?? '';
        $this->pexels_key = $opts['pexels_api_key'] ?? '';
    }

    private function build_placeholder_content( string $topic, int $target_words ) : array {
        /* translators: %s: topic */
        $title = sprintf( __( '%s: What You Need To Know', 'trendly-ai-post' ), $topic );
        // Do NOT include H1 to avoid duplicate titles on frontend
        $content  = '<p>' . esc_html__( 'This article was generated using a fallback template. Configure your Gemini API key for richer AI content.', 'trendly-ai-post' ) . '</p>';

        $sections = [
            __( 'Background', 'trendly-ai-post' ),
            __( 'Key Developments', 'trendly-ai-post' ),
            __( 'Impact', 'trendly-ai-post' ),
            __( 'What Next', 'trendly-ai-post' ),
        ];

        // Build human-like varied paragraphs per section
        foreach ( $sections as $label ) {
            $content .= '<h2>' . esc_html( $label ) . '</h2>';
            /* translators: %s: topic */
            $p1 = sprintf( __( 'This section provides context on %s and outlines why the story matters now.', 'trendly-ai-post' ), $topic );
            /* translators: %s: topic */
            $p2 = sprintf( __( 'It summarizes verifiable facts available at the time of writing about %s, while avoiding speculation.', 'trendly-ai-post' ), $topic );
            /* translators: %s: topic */
            $p3 = sprintf( __( 'Where relevant, it highlights key people, places, and timelines connected to %s.', 'trendly-ai-post' ), $topic );
            $content .= '<p>' . esc_html( $p1 ) . '</p>';
            $content .= '<p>' . esc_html( $p2 ) . '</p>';
            $content .= '<p>' . esc_html( $p3 ) . '</p>';
        }

        // Aim to roughly meet target words by appending a concise key points list
        $content .= '<h2>' . esc_html__( 'Key Points', 'trendly-ai-post' ) . '</h2>';
        $content .= '<ul>';
        /* translators: %s: topic */
        $content .= '<li>' . esc_html( sprintf( __( 'What happened: a brief rundown related to %s.', 'trendly-ai-post' ), $topic ) ) . '</li>';
        /* translators: %s: topic */
        $content .= '<li>' . esc_html( sprintf( __( 'Why it matters: short context for readers following %s.', 'trendly-ai-post' ), $topic ) ) . '</li>';
        /* translators: %s: topic */
        $content .= '<li>' . esc_html( sprintf( __( 'What to watch: upcoming milestones or official statements around %s.', 'trendly-ai-post' ), $topic ) ) . '</li>';
        $content .= '</ul>';

        return [
            'title' => $title,
            /* translators: %s: topic */
            'meta_description' => sprintf( __( 'Latest insights on %s with key facts and context.', 'trendly-ai-post' ), $topic ),
            'content' => $content,
            'keywords' => [ $topic ],
        ];
    }

    public function is_configured() : bool {
        return ! empty( $this->gemini_key ) && ! empty( $this->pexels_key );
    }

    public function fetch_trending_topics( string $region_code = 'IN', int $limit = 10 ) : array {
        // Google News RSS region map simplified; can be expanded later
        $region_map = [
            'IN' => 'hl=en-IN&gl=IN&ceid=IN:en',
            'US' => 'hl=en-US&gl=US&ceid=US:en',
            'GB' => 'hl=en-GB&gl=GB&ceid=GB:en',
            'PK' => 'hl=en-PK&gl=PK&ceid=PK:en',
            'CA' => 'hl=en-CA&gl=CA&ceid=CA:en',
            'AU' => 'hl=en-AU&gl=AU&ceid=AU:en',
            'DE' => 'hl=de&gl=DE&ceid=DE:de',
            'FR' => 'hl=fr&gl=FR&ceid=FR:fr',
            'JP' => 'hl=ja&gl=JP&ceid=JP:ja',
            'CN' => 'hl=zh-CN&gl=CN&ceid=CN:zh-Hans',
            'BR' => 'hl=pt-BR&gl=BR&ceid=BR:pt-419',
            'RU' => 'hl=ru&gl=RU&ceid=RU:ru',
            'ZA' => 'hl=en-ZA&gl=ZA&ceid=ZA:en',
            'NG' => 'hl=en-NG&gl=NG&ceid=NG:en',
            'KE' => 'hl=en-KE&gl=KE&ceid=KE:en',
            'EG' => 'hl=ar&gl=EG&ceid=EG:ar',
            'AE' => 'hl=ar&gl=AE&ceid=AE:ar',
            'SA' => 'hl=ar&gl=SA&ceid=SA:ar',
            'SG' => 'hl=en-SG&gl=SG&ceid=SG:en',
            'MY' => 'hl=en-MY&gl=MY&ceid=MY:en',
            'TH' => 'hl=th&gl=TH&ceid=TH:th',
            'ID' => 'hl=id&gl=ID&ceid=ID:id',
            'PH' => 'hl=en-PH&gl=PH&ceid=PH:en',
            'BD' => 'hl=bn&gl=BD&ceid=BD:bn',
            'LK' => 'hl=en-LK&gl=LK&ceid=LK:en',
        ];
        $query = $region_map[ $region_code ] ?? $region_map['IN'];
        $url   = 'https://news.google.com/rss?' . $query;

        $resp = wp_remote_get( $url, [ 'timeout' => 10 ] );
        if ( is_wp_error( $resp ) ) {
            return [];
        }
        $body = wp_remote_retrieve_body( $resp );
        if ( empty( $body ) ) {
            return [];
        }
        $items = [];
        $rss = @simplexml_load_string( $body );
        if ( $rss && isset( $rss->channel->item ) ) {
            foreach ( $rss->channel->item as $item ) {
                $title = (string) $item->title;
                if ( ! empty( $title ) ) {
                    $items[] = html_entity_decode( wp_strip_all_tags( $title ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
                }
            }
        }
        // Deduplicate, randomize order, and cap to limit so each fetch click can show different topics
        $items = array_values( array_unique( $items ) );
        if ( count( $items ) > 1 ) {
            shuffle( $items );
        }
        if ( $limit > 0 && count( $items ) > $limit ) {
            $items = array_slice( $items, 0, $limit );
        }
        return $items;
    }

    public function generate_content_with_gemini( string $topic, string $length = 'medium', string $model = 'gemini-2.5-flash' ) : array {
        // Returns associative array: ['title' => string, 'content' => string, 'meta_description' => string, 'keywords' => array]
        $word_counts = [ 'short' => 1000, 'medium' => 1500, 'long' => 3000, 'extra' => 4500 ];
        $wc = $word_counts[ $length ] ?? 700;

        if ( empty( $this->gemini_key ) ) {
            return $this->build_placeholder_content( $topic, $wc );
        }

        $prompt = $this->build_gemini_prompt( $topic, $wc );
        $endpoint = sprintf( 'https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s', rawurlencode( $model ), rawurlencode( $this->gemini_key ) );
        $payload = [
            'generationConfig' => [
                'temperature' => 0.7,
                'topP' => 0.9,
                'maxOutputTokens' => 8192,
            ],
            'contents' => [ [ 'parts' => [ [ 'text' => $prompt ] ] ] ],
        ];

        $resp = wp_remote_post( $endpoint, [
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => wp_json_encode( $payload ),
            'timeout' => 120,
        ] );

        if ( is_wp_error( $resp ) ) {
            return [ 'title' => $topic, 'content' => '<p>' . esc_html( $resp->get_error_message() ) . '</p>', 'meta_description' => '', 'keywords' => [ $topic ] ];
        }
        $code = wp_remote_retrieve_response_code( $resp );
        $body = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
        if ( $code !== 200 || empty( $body['candidates'][0]['content']['parts'][0]['text'] ) ) {
            return $this->build_placeholder_content( $topic, $wc );
        }

        $raw = (string) $body['candidates'][0]['content']['parts'][0]['text'];
        // Remove fenced code blocks like ```html and closing ```
        $raw = preg_replace( '/```[a-zA-Z]*\s*/', '', $raw );
        $raw = str_replace( '```', '', $raw );
        $html = $this->parse_markdown_to_html( $raw );
        // Remove any H1s to prevent duplicate titles on the frontend (support attributes)
        $html = preg_replace( '/<h1[^>]*>.*?<\/h1>/si', '', $html );
        // Convert Markdown bold (**text**) to <strong>text</strong>
        $html = preg_replace( '/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $html );
        // Remove stray leading asterisks in paragraphs like "* " or "* *" that may appear from lists
        $html = preg_replace( '/<p>\s*(?:\*\s*)+/', '<p>', $html );
        // Emphasize leading label phrases like "Connectivity:" or "Design and Build:" at paragraph start
        // Only bold the label part before the colon to avoid over-highlighting entire paragraphs.
        $html = preg_replace( '/<p>\s*([\p{L}0-9][^:<]{2,80}):\s*/u', '<p><strong>$1:</strong> ', $html );
        $title = $this->extract_title_from_html( $html );
        if ( empty( $title ) ) {
            $title = $topic;
        }
        $meta = $this->extract_first_paragraph( $html );
        if ( empty( $meta ) ) {
            /* translators: %s: topic */
            $meta = sprintf( __( 'Latest insights on %s with key facts and context.', 'trendly-ai-post' ), $topic );
        }

        return [
            'title' => $title,
            'content' => $html,
            'meta_description' => $meta,
            'keywords' => [ $topic ],
        ];
    }

    private function build_gemini_prompt( string $topic, int $target_words ) : string {
        $instructions = __( 'Write a news article in clean HTML (no inline styles). Tone: neutral, concise, human-like. Use short paragraphs, specific facts, entities, dates, and places. Avoid repetition and filler.', 'trendly-ai-post' );
        $outline = __( 'Structure:\n- H1: SEO title (<= 70 chars)\n- Intro: 2-3 sentences (what/where/when)\n- H2: Background (context and timeline)\n- H2: Key developments (recent changes)\n- H2: Impact (who is affected)\n- H2: What next (expected milestones)\n- Optional H3s for details\n- Do not include sources or code fences', 'trendly-ai-post' );
        /* translators: 1: topic, 2: target word count, 3: writing instructions, 4: required outline */
        return sprintf( __( "Topic: %1\$s\nTarget length: about %2\$d words\n\n%3\$s\n\n%4\$s", 'trendly-ai-post' ), $topic, $target_words, $instructions, $outline );
    }

    private function parse_markdown_to_html( string $raw ) : string {
        // Convert markdown-like headings to HTML and wrap paragraphs
        $html = preg_replace( '/^#\s*(.+)$/m', '<h1>$1</h1>', (string) $raw );
        $html = preg_replace( '/^##\s*(.+)$/m', '<h2>$1</h2>', (string) $html );
        $html = preg_replace( '/^###\s*(.+)$/m', '<h3>$1</h3>', (string) $html );
        $chunks = preg_split( '/\n\n+/', (string) $html );
        $chunks = array_map( function( $c ) {
            $c = trim( $c );
            if ( $c === '' ) return '';
            if ( preg_match( '/^<h[1-3]>/', $c ) ) return $c;
            return '<p>' . esc_html( wp_strip_all_tags( $c ) ) . '</p>';
        }, $chunks );
        return implode( "\n", array_filter( $chunks ) );
    }

    private function extract_title_from_html( string $html ) : string {
        if ( preg_match( '/<h1>(.*?)<\/h1>/', $html, $m ) ) {
            return wp_strip_all_tags( $m[1] );
        }
        return '';
    }

    private function extract_first_paragraph( string $html ) : string {
        if ( preg_match( '/<p>(.*?)<\/p>/', $html, $m ) ) {
            $desc = wp_strip_all_tags( $m[1] );
            return mb_substr( $desc, 0, 160 );
        }
        return '';
    }

    public function fetch_images_from_pexels( string $query, int $count = 1 ) : array {
        $count = max( 1, min( 4, $count ) );
        if ( empty( $this->pexels_key ) ) {
            // Provide a small pool of varied placeholder images (local assets)
            $pool = [
                plugin_dir_url( __FILE__ ) . '../../assets/placeholder1.jpg',
                plugin_dir_url( __FILE__ ) . '../../assets/placeholder2.jpg',
                plugin_dir_url( __FILE__ ) . '../../assets/placeholder3.jpg',
                plugin_dir_url( __FILE__ ) . '../../assets/placeholder4.jpg',
                plugin_dir_url( __FILE__ ) . '../../assets/placeholder5.jpg',
            ];
            shuffle( $pool );
            return array_slice( $pool, 0, max( 1, min( 4, $count ) ) );
        }
        $endpoint = add_query_arg( [
            'query' => $query,
            'orientation' => 'landscape',
            'size' => 'large',
            'per_page' => $count,
        ], 'https://api.pexels.com/v1/search' );
        $resp = wp_remote_get( $endpoint, [
            'timeout' => 20,
            'headers' => [ 'Authorization' => $this->pexels_key ],
        ] );
        if ( is_wp_error( $resp ) ) {
            return [];
        }
        $body = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
        if ( empty( $body['photos'] ) ) {
            return [];
        }
        $urls = [];
        foreach ( $body['photos'] as $photo ) {
            if ( ! empty( $photo['src']['large'] ) ) {
                $urls[] = esc_url_raw( $photo['src']['large'] );
            }
        }
        return $urls;
    }
}
