<?php
/**
 * DBA Startup Hub Kaizen — Learning Engine
 *
 * Thin wrapper around the core DBA_Kaizen engine, namespaced for
 * Startup Hub so it can store and retrieve learning data independently.
 *
 * Delegates to the core Kaizen engine when available, but works
 * standalone if the core class is not loaded.
 *
 * @since 2.16.0
 */

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

class DBA_Startup_Hub_Kaizen {

    const META_ORIGINAL_CONTENT = '_dba_startup_hub_original_content';
    const META_ORIGINAL_TITLE   = '_dba_startup_hub_original_title';
    const META_ORIGINAL_EXCERPT = '_dba_startup_hub_original_excerpt';
    const TRANSIENT_KEY         = 'dba_startup_hub_kaizen_context';
    const LOOKBACK_DAYS         = 5;

    /**
     * Get learning context string to append to the system prompt.
     *
     * Delegates to core DBA_Kaizen when available, otherwise builds
     * a Startup Hub-specific context from recent corrections.
     *
     * @return string Prompt injection string (may be empty).
     */
    public static function get_learning_context() {
        // Try core Kaizen first
        if ( class_exists( 'DBA_Kaizen' ) && method_exists( 'DBA_Kaizen', 'get_learning_context' ) ) {
            return DBA_Kaizen::get_learning_context();
        }

        // Standalone mode: check cache
        $cached = get_transient( self::TRANSIENT_KEY );
        if ( $cached !== false ) {
            return $cached;
        }

        // Build context from recent Startup Hub post corrections
        $context = self::build_context();
        set_transient( self::TRANSIENT_KEY, $context, 6 * HOUR_IN_SECONDS );

        return $context;
    }

    /**
     * Store the original AI-generated content for later comparison.
     *
     * @param int    $post_id
     * @param string $title
     * @param string $content
     * @param string $excerpt
     */
    public static function store_original( $post_id, $title, $content, $excerpt ) {
        // Store in Startup Hub-specific meta
        update_post_meta( $post_id, self::META_ORIGINAL_TITLE,   $title );
        update_post_meta( $post_id, self::META_ORIGINAL_CONTENT, $content );
        update_post_meta( $post_id, self::META_ORIGINAL_EXCERPT, $excerpt );

        // Also store in core Kaizen meta if available
        if ( class_exists( 'DBA_Kaizen' ) && method_exists( 'DBA_Kaizen', 'store_original' ) ) {
            DBA_Kaizen::store_original( $post_id, $title, $content, $excerpt );
        } else {
            // Fallback: store in the standard core meta keys too
            update_post_meta( $post_id, '_dba_original_title',   $title );
            update_post_meta( $post_id, '_dba_original_content', $content );
        }

        // Invalidate cache so next generation picks up corrections
        delete_transient( self::TRANSIENT_KEY );
    }

    /**
     * Build learning context from recent Startup Hub corrections.
     *
     * @return string
     */
    private static function build_context() {
        $config = DBA_Startup_Hub_Registry::get_config();

        $recent = get_posts( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft' ),
            'meta_key'       => $config['meta_auto_created'],
            'meta_compare'   => 'EXISTS',
            'posts_per_page' => 20,
            'fields'         => 'ids',
            'date_query'     => array( array( 'after' => self::LOOKBACK_DAYS . ' days ago' ) ),
            'orderby'        => 'date',
            'order'          => 'DESC',
        ) );

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

        $corrections = array();

        foreach ( $recent as $pid ) {
            $original_title   = get_post_meta( $pid, self::META_ORIGINAL_TITLE, true );
            $original_content = get_post_meta( $pid, self::META_ORIGINAL_CONTENT, true );

            if ( empty( $original_content ) ) continue;

            $current_title   = get_the_title( $pid );
            $current_content = get_post_field( 'post_content', $pid );

            // Check for title correction
            if ( ! empty( $original_title ) && $original_title !== $current_title ) {
                $corrections[] = "TITLE CORRECTION: \"{$original_title}\" → \"{$current_title}\"";
            }

            // Check for significant content changes (more than 5% different)
            $original_words = str_word_count( strip_tags( $original_content ) );
            $current_words  = str_word_count( strip_tags( $current_content ) );

            if ( $original_words > 0 ) {
                $diff_pct = abs( $current_words - $original_words ) / $original_words * 100;
                if ( $diff_pct > 5 ) {
                    $corrections[] = "CONTENT EDIT on post #{$pid}: word count changed from {$original_words} to {$current_words} ({$diff_pct}% change)";
                }
            }

            // Check for H2 changes
            preg_match_all( '/<h2[^>]*>(.*?)<\/h2>/si', $original_content, $orig_h2s );
            preg_match_all( '/<h2[^>]*>(.*?)<\/h2>/si', $current_content, $curr_h2s );
            $orig_h2_list = array_map( 'strip_tags', $orig_h2s[1] ?? array() );
            $curr_h2_list = array_map( 'strip_tags', $curr_h2s[1] ?? array() );

            $added_h2s   = array_diff( $curr_h2_list, $orig_h2_list );
            $removed_h2s = array_diff( $orig_h2_list, $curr_h2_list );

            if ( ! empty( $added_h2s ) ) {
                $corrections[] = "HEADINGS ADDED on #{$pid}: " . implode( ', ', array_slice( $added_h2s, 0, 3 ) );
            }
            if ( ! empty( $removed_h2s ) ) {
                $corrections[] = "HEADINGS REMOVED on #{$pid}: " . implode( ', ', array_slice( $removed_h2s, 0, 3 ) );
            }
        }

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

        $context = "\n\n══ KAIZEN — EDITOR CORRECTIONS (learn from these) ══\n"
            . "The following corrections were made by a human editor on recent Startup Hub posts.\n"
            . "Apply these patterns to improve your output:\n\n"
            . implode( "\n", array_slice( $corrections, 0, 10 ) )
            . "\n══════════════════════════════════════════════════════\n";

        return $context;
    }
}
