<?php
/**
 * LuxStrat International — Self-Improvement Engine
 *
 * ═══════════════════════════════════════════════════════════════════════
 *  PURPOSE: Before generating a new post, read the 5 latest published
 *  LuxStrat posts (which may have been manually corrected by the editor)
 *  and extract writing patterns, link style, SEO approach, structure.
 *  Feed this as a prompt block to OpenAI so it mimics the editor's style.
 *
 *  NO HOOKS. NO SAVE TRACKING. NO DIFFS.
 *  Just reads what's live on the site and learns from it.
 *
 *  Called once by the generator before each OpenAI API call.
 * ═══════════════════════════════════════════════════════════════════════
 *
 * @since 2.14.0
 * @package DamalionBlogAI
 * @subpackage LuxStratIntl
 */

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

class DBA_LuxStrat_Intl_Corrections {

    /** How many recent posts to analyze */
    const POSTS_TO_ANALYZE = 5;

    /**
     * Read the N latest published LuxStrat posts, analyze their content,
     * and build a prompt block for OpenAI.
     *
     * @param string $lang        Language code.
     * @param string $theme_slug  Current theme being generated (for context).
     * @return string Prompt block (empty if no posts to learn from).
     */
    public static function build_learning_prompt( $lang, $theme_slug = '' ) {
        $prefix = DBA_LuxStrat_Intl_Dedupe::meta_prefix( $lang );

        $posts = get_posts( array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => self::POSTS_TO_ANALYZE,
            'orderby'        => 'date',
            'order'          => 'DESC',
            'meta_query'     => array(
                array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ),
            ),
            'suppress_filters' => false,
        ) );

        if ( empty( $posts ) ) return '';

        $analyses = array();
        foreach ( $posts as $post ) {
            $analyses[] = self::analyze_post( $post, $prefix );
        }

        return self::compile_prompt( $analyses, $lang, $theme_slug );
    }

    /* =================================================================
     *  ANALYZE A SINGLE POST
     * ================================================================= */

    private static function analyze_post( $post, $prefix ) {
        $content = $post->post_content;
        $plain   = wp_strip_all_tags( $content );

        // ── Structure ──
        $h2s = array();
        if ( preg_match_all( '/<h2[^>]*>(.*?)<\/h2>/si', $content, $m ) ) {
            $h2s = array_map( 'wp_strip_all_tags', $m[1] );
        }
        $h3s = array();
        if ( preg_match_all( '/<h3[^>]*>(.*?)<\/h3>/si', $content, $m ) ) {
            $h3s = array_map( 'wp_strip_all_tags', $m[1] );
        }

        // ── Paragraphs ──
        $para_count = 0;
        $para_lengths = array();
        if ( preg_match_all( '/<p[^>]*>(.*?)<\/p>/si', $content, $m ) ) {
            foreach ( $m[1] as $p ) {
                $ptxt = trim( wp_strip_all_tags( $p ) );
                if ( mb_strlen( $ptxt ) > 20 ) {
                    $para_count++;
                    $para_lengths[] = mb_strlen( $ptxt );
                }
            }
        }

        // ── Internal links ──
        $internal_links = array();
        if ( preg_match_all( '/<a[^>]+href=["\']([^"\']*damalion\.com[^"\']*)["\'][^>]*>(.*?)<\/a>/si', $content, $m, PREG_SET_ORDER ) ) {
            foreach ( $m as $link ) {
                $internal_links[] = array(
                    'url'    => $link[1],
                    'anchor' => trim( wp_strip_all_tags( $link[2] ) ),
                );
            }
        }

        // ── CTA ──
        $cta_text = '';
        if ( preg_match( '/<p[^>]*>[^<]*<a[^>]+href=["\'][^"\']*contact[^"\']*["\'][^>]*>.*?<\/a>[^<]*<\/p>\s*$/si', $content, $cta_match ) ) {
            $cta_text = trim( wp_strip_all_tags( $cta_match[0] ) );
        }

        // ── SEO ──
        $meta_desc = get_post_meta( $post->ID, '_yoast_wpseo_metadesc', true );
        if ( empty( $meta_desc ) ) $meta_desc = get_post_meta( $post->ID, 'rank_math_description', true );
        $focus_kw = get_post_meta( $post->ID, '_yoast_wpseo_focuskw', true );
        if ( empty( $focus_kw ) ) $focus_kw = get_post_meta( $post->ID, 'rank_math_focus_keyword', true );

        // ── Featured image alt ──
        $img_alt = '';
        $thumb_id = get_post_thumbnail_id( $post->ID );
        if ( $thumb_id ) {
            $img_alt = get_post_meta( $thumb_id, '_wp_attachment_image_alt', true );
        }

        // ── Word count & sentences ──
        $word_count = str_word_count( $plain );
        $sentences  = preg_split( '/[.!?]+/u', $plain, -1, PREG_SPLIT_NO_EMPTY );
        $sentence_count   = count( $sentences );
        $avg_sentence_len = $sentence_count > 0 ? round( $word_count / $sentence_count, 1 ) : 0;

        return array(
            'title'            => $post->post_title,
            'theme'            => get_post_meta( $post->ID, $prefix . 'theme_label', true ),
            'word_count'       => $word_count,
            'h2_list'          => $h2s,
            'h3_list'          => $h3s,
            'para_count'       => $para_count,
            'avg_para_length'  => ! empty( $para_lengths ) ? round( array_sum( $para_lengths ) / count( $para_lengths ) ) : 0,
            'internal_links'   => $internal_links,
            'cta_text'         => $cta_text,
            'meta_desc'        => $meta_desc ?: '',
            'focus_keyword'    => $focus_kw ?: '',
            'img_alt'          => $img_alt ?: '',
            'avg_sentence_len' => $avg_sentence_len,
        );
    }

    /* =================================================================
     *  COMPILE PROMPT
     * ================================================================= */

    private static function compile_prompt( $analyses, $lang, $theme_slug ) {
        if ( empty( $analyses ) ) return '';

        $n = count( $analyses );

        // ── Averages ──
        $avg_words    = round( array_sum( array_column( $analyses, 'word_count' ) ) / $n );
        $avg_h2       = round( count( $analyses[0]['h2_list'] ?? array() ) ); // use most recent as reference
        $avg_h3       = round( count( $analyses[0]['h3_list'] ?? array() ) );
        $avg_paras    = round( array_sum( array_column( $analyses, 'para_count' ) ) / $n );
        $avg_para_len = round( array_sum( array_column( $analyses, 'avg_para_length' ) ) / $n );
        $avg_sent_len = round( array_sum( array_column( $analyses, 'avg_sentence_len' ) ) / $n, 1 );

        // Internal link URLs (deduplicated, ranked by frequency)
        $link_freq = array();
        $link_anchors = array();
        foreach ( $analyses as $a ) {
            foreach ( $a['internal_links'] as $lk ) {
                $key = strtolower( rtrim( $lk['url'], '/' ) );
                $link_freq[ $key ] = ( $link_freq[ $key ] ?? 0 ) + 1;
                if ( ! isset( $link_anchors[ $key ] ) ) $link_anchors[ $key ] = $lk['anchor'];
            }
        }
        arsort( $link_freq );
        $avg_links = $n > 0 ? round( array_sum( array_map( function( $a ) { return count( $a['internal_links'] ); }, $analyses ) ) / $n, 1 ) : 0;

        // SEO
        $meta_samples  = array_filter( array_column( $analyses, 'meta_desc' ) );
        $kw_samples    = array_filter( array_column( $analyses, 'focus_keyword' ) );
        $alt_samples   = array_filter( array_column( $analyses, 'img_alt' ) );
        $cta_samples   = array_filter( array_column( $analyses, 'cta_text' ) );

        // H2 examples from all posts
        $all_h2s = array();
        foreach ( $analyses as $a ) $all_h2s = array_merge( $all_h2s, $a['h2_list'] );

        // ── Build prompt ──
        $lines = array();
        $lines[] = 'LEARN FROM THE ' . $n . ' MOST RECENT PUBLISHED ARTICLES — follow these patterns closely:';
        $lines[] = '';

        // Structure
        $lines[] = 'ARTICLE STRUCTURE:';
        $lines[] = '- Word count: ~' . $avg_words . ' words. Match this.';
        $lines[] = '- H2 sections: ' . $avg_h2 . '. H3 sub-sections: ' . $avg_h3 . '.';
        $lines[] = '- Paragraphs: ~' . $avg_paras . ', each ~' . $avg_para_len . ' chars.';
        $lines[] = '- Avg sentence length: ' . $avg_sent_len . ' words.';

        // H2 tone
        if ( ! empty( $all_h2s ) ) {
            $lines[] = '';
            $lines[] = 'H2 HEADING STYLE (match this tone):';
            foreach ( array_slice( array_unique( $all_h2s ), 0, 8 ) as $h2 ) {
                $lines[] = '  - "' . $h2 . '"';
            }
        }

        // Internal links
        $lines[] = '';
        $lines[] = 'INTERNAL LINKS (~' . $avg_links . ' per post):';
        if ( ! empty( $link_freq ) ) {
            foreach ( array_slice( $link_freq, 0, 8, true ) as $url => $count ) {
                $anchor = $link_anchors[ $url ] ?? '';
                $lines[] = '  - ' . $url . ( $anchor ? ' (anchor: "' . $anchor . '")' : '' );
            }
            $lines[] = 'Link to these URLs naturally when the topic is relevant.';
        }

        // SEO
        $lines[] = '';
        $lines[] = 'SEO:';
        if ( ! empty( $meta_samples ) ) {
            $avg_meta = round( array_sum( array_map( 'mb_strlen', $meta_samples ) ) / count( $meta_samples ) );
            $lines[] = '- Meta description: ~' . $avg_meta . ' chars. Example: "' . mb_substr( $meta_samples[0], 0, 100 ) . '..."';
        }
        if ( ! empty( $kw_samples ) ) {
            $lines[] = '- Focus keyword style: "' . implode( '", "', array_slice( $kw_samples, 0, 4 ) ) . '"';
        }
        if ( ! empty( $alt_samples ) ) {
            $avg_alt = round( array_sum( array_map( 'mb_strlen', $alt_samples ) ) / count( $alt_samples ) );
            $lines[] = '- Image alt: ~' . $avg_alt . ' chars. Example: "' . mb_substr( $alt_samples[0], 0, 80 ) . '"';
        }

        // CTA
        if ( ! empty( $cta_samples ) ) {
            $lines[] = '';
            $lines[] = 'CTA (close with a similar line):';
            $lines[] = '- "' . $cta_samples[0] . '"';
        }

        return "\n\n" . implode( "\n", $lines );
    }
}
