<?php
/**
 * DBA Pipeline Test — TEMPORARY FILE
 * Upload to plugin root. Delete after testing.
 *
 * Usage:
 *   /wp-admin/?dba_pipeline=harvest   → Stage 1: pull Google keywords
 *   /wp-admin/?dba_pipeline=validate  → Stage 2: OpenAI validates + creates briefs
 *   /wp-admin/?dba_pipeline=stats     → View brief queue + pipeline status
 *   /wp-admin/?dba_pipeline=flush     → Clear all briefs (reset queue)
 *
 * @since 2.20.0
 */

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

add_action( 'admin_init', function() {
    if ( ! isset( $_GET['dba_pipeline'] ) ) return;
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Forbidden' );

    if ( ! class_exists( 'DBA_TIS_Pipeline' ) ) {
        wp_die( '❌ DBA_TIS_Pipeline class not loaded. Check that class-tis-pipeline.php is in the tis/ folder.' );
    }

    $action = sanitize_key( $_GET['dba_pipeline'] );
    $pipeline = DBA_TIS_Pipeline::get_instance();

    switch ( $action ) {

        case 'harvest':
            // Timeout guard — Serper calls can take 30+ seconds with 30 calls
            if ( function_exists( 'set_time_limit' ) ) @set_time_limit( 120 );
            if ( function_exists( 'ignore_user_abort' ) ) @ignore_user_abort( true );
            echo '<h2>🌾 Running Pipeline Harvest (Stage 1)...</h2>';
            echo '<p>Querying Serper API for Google keywords from TIS gaps.</p>';
            flush();
            $pipeline->run_harvest();
            echo '<h3>✅ Harvest complete.</h3>';
            echo '<p><a href="' . admin_url( '?dba_pipeline=stats' ) . '">→ View stats</a></p>';
            echo '<p>Check <code>error_log</code> for details.</p>';
            wp_die();

        case 'validate':
            // Timeout guard — OpenAI calls can take 30+ seconds each
            if ( function_exists( 'set_time_limit' ) ) @set_time_limit( 180 );
            if ( function_exists( 'ignore_user_abort' ) ) @ignore_user_abort( true );
            echo '<h2>🧪 Running Pipeline Validate (Stage 2)...</h2>';
            echo '<p>Sending harvested keywords to OpenAI for legal validation + brief generation.</p>';
            flush();
            $pipeline->run_validate();
            echo '<h3>✅ Validate complete.</h3>';
            echo '<p><a href="' . admin_url( '?dba_pipeline=stats' ) . '">→ View stats</a></p>';
            echo '<p>Check <code>error_log</code> for details.</p>';
            wp_die();

        case 'stats':
            $stats = DBA_TIS_Pipeline::get_stats();
            echo '<div style="font-family:monospace;max-width:900px;margin:20px auto;">';
            echo '<h2>📊 Pipeline Status</h2>';

            // Brief counts
            echo '<h3>Article Briefs</h3>';
            echo '<table border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse;">';
            echo '<tr><th>Status</th><th>Count</th></tr>';
            echo '<tr><td style="color:#0073aa;font-weight:bold;">PENDING</td><td>' . ( $stats['pending'] ?? 0 ) . '</td></tr>';
            echo '<tr><td style="color:#ffb900;font-weight:bold;">CONSUMED</td><td>' . ( $stats['consumed'] ?? 0 ) . '</td></tr>';
            echo '<tr><td style="color:#46b450;font-weight:bold;">PUBLISHED</td><td>' . ( $stats['published'] ?? 0 ) . '</td></tr>';
            echo '<tr><td><strong>TOTAL</strong></td><td><strong>' . ( $stats['total_briefs'] ?? 0 ) . '</strong></td></tr>';
            echo '</table>';

            // Per-bot distribution
            $bot_dist = array();
            foreach ( $all_briefs as $b ) {
                $bot = $b['bot_id'] ?? 'unknown';
                if ( ! isset( $bot_dist[ $bot ] ) ) $bot_dist[ $bot ] = array( 'pending' => 0, 'consumed' => 0, 'published' => 0 );
                $status = $b['status'] ?? 'pending';
                if ( isset( $bot_dist[ $bot ][ $status ] ) ) $bot_dist[ $bot ][ $status ]++;
            }
            if ( ! empty( $bot_dist ) ) {
                echo '<h3>🤖 Briefs per Bot</h3>';
                echo '<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;font-size:12px;">';
                echo '<tr><th>Bot</th><th>Pending</th><th>Consumed</th><th>Published</th><th>Total</th></tr>';
                foreach ( $bot_dist as $bname => $bc ) {
                    $bt = $bc['pending'] + $bc['consumed'] + $bc['published'];
                    echo '<tr><td><strong>' . esc_html( $bname ) . '</strong></td>';
                    echo '<td>' . $bc['pending'] . '</td><td>' . $bc['consumed'] . '</td><td>' . $bc['published'] . '</td>';
                    echo '<td><strong>' . $bt . '</strong></td></tr>';
                }
                echo '</table>';
            }

            // Pending briefs detail
            $all_briefs = DBA_TIS_Pipeline::get_all_briefs();
            $pending = array_filter( $all_briefs, function( $b ) { return ( $b['status'] ?? '' ) === 'pending'; } );
            if ( ! empty( $pending ) ) {
                echo '<h3>📋 Pending Briefs (' . count( $pending ) . ' waiting for bots)</h3>';
                echo '<table border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse;width:100%;">';
                echo '<tr><th>#</th><th>Bot</th><th>Theme</th><th>Title</th><th>Keywords</th><th>Priority</th></tr>';
                $i = 1;
                foreach ( $pending as $b ) {
                    echo '<tr>';
                    echo '<td>' . $i++ . '</td>';
                    echo '<td><strong>' . esc_html( $b['bot_id'] ?? '' ) . '</strong></td>';
                    echo '<td>' . esc_html( $b['theme_slug'] ?? '' ) . '</td>';
                    echo '<td>' . esc_html( $b['title'] ?? '' ) . '</td>';
                    echo '<td><small>' . esc_html( implode( ', ', $b['keywords'] ?? array() ) ) . '</small></td>';
                    echo '<td>' . esc_html( $b['priority'] ?? '' ) . '</td>';
                    echo '</tr>';
                }
                echo '</table>';
            } else {
                echo '<p style="color:#999;">No pending briefs. Run harvest + validate first.</p>';
            }

            // Harvest stats
            echo '<h3>🌾 Harvest Data</h3>';
            $harvest = get_option( 'dba_pipeline_harvested_keywords', array() );
            $topics  = $harvest['topics'] ?? array();
            if ( empty( $topics ) ) {
                echo '<p style="color:#999;">No harvest data yet. Run harvest first.</p>';
            } else {
                echo '<p>Serper calls: <strong>' . ( $harvest['serper_calls'] ?? 0 ) . '</strong> | Topics: <strong>' . count( $topics ) . '</strong></p>';
                echo '<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%;font-size:12px;">';
                echo '<tr><th>Keyword</th><th>Bot</th><th>Grade</th><th>Related</th><th>PAA</th><th>Fallback</th><th>Competitors</th></tr>';
                foreach ( $topics as $t ) {
                    $rel_c  = count( $t['related_searches'] ?? array() );
                    $paa_c  = count( $t['people_also_ask'] ?? array() );
                    $fb_c   = count( $t['fallback_keywords'] ?? array() );
                    $comp_c = count( $t['competitor_titles'] ?? array() );
                    echo '<tr>';
                    echo '<td><strong>' . esc_html( $t['root_keyword'] ?? '' ) . '</strong></td>';
                    echo '<td>' . esc_html( $t['target_bot'] ?? 'luxstrat' ) . '</td>';
                    echo '<td>' . esc_html( $t['grade'] ?? '?' ) . '</td>';
                    echo '<td>' . $rel_c . '</td>';
                    echo '<td>' . $paa_c . '</td>';
                    echo '<td>' . $fb_c . '</td>';
                    echo '<td>' . $comp_c . '</td>';
                    echo '</tr>';
                }
                echo '</table>';
            }

            // Scheduling
            echo '<h3>⏰ Next Scheduled Runs</h3>';
            echo '<p>Harvest: <code>' . ( $stats['next_harvest'] ?? 'Not scheduled' ) . '</code></p>';
            echo '<p>Validate: <code>' . ( $stats['next_validate'] ?? 'Not scheduled' ) . '</code></p>';

            // Recent log
            echo '<h3>📜 Recent Log</h3>';
            $log = get_option( 'dba_pipeline_log', array() );
            if ( empty( $log ) ) {
                echo '<p style="color:#999;">No log entries yet.</p>';
            } else {
                echo '<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%;font-size:12px;">';
                echo '<tr><th>Time</th><th>Stage</th><th>Message</th></tr>';
                foreach ( array_slice( $log, 0, 20 ) as $entry ) {
                    echo '<tr>';
                    echo '<td><code>' . esc_html( $entry['time'] ?? '' ) . '</code></td>';
                    echo '<td>' . esc_html( $entry['stage'] ?? '' ) . '</td>';
                    echo '<td>' . esc_html( $entry['message'] ?? '' ) . '</td>';
                    echo '</tr>';
                }
                echo '</table>';
            }

            echo '<h3>🔧 Actions</h3>';
            echo '<p>';
            echo '<a href="' . admin_url( '?dba_pipeline=harvest' ) . '" style="margin-right:15px;">🌾 Run Harvest</a>';
            echo '<a href="' . admin_url( '?dba_pipeline=validate' ) . '" style="margin-right:15px;">🧪 Run Validate</a>';
            echo '<a href="' . admin_url( '?dba_pipeline=flush' ) . '" style="color:#dc3232;">🗑️ Flush All Briefs</a>';
            echo '</p>';

            echo '</div>';
            wp_die();

        case 'flush':
            delete_option( 'dba_pipeline_article_briefs' );
            delete_option( 'dba_pipeline_harvested_keywords' );
            echo '<h2>🗑️ Pipeline queue flushed.</h2>';
            echo '<p><a href="' . admin_url( '?dba_pipeline=stats' ) . '">→ Back to stats</a></p>';
            wp_die();

        default:
            wp_die( 'Unknown action: ' . esc_html( $action ) );
    }
});
