<?php
defined('ABSPATH') or die();

/*
 * Bulk article quality enhancements for Aimogen Pro.
 *
 * - Final AI editor pass (coherence, deduplication, SEO structure)
 * - Yoast / Rank Math / etc. meta description + focus keyword
 * - Safer post-processing (skip grammar-breaking "undetectability" tweaks)
 * - One-time migration of sensible global defaults
 */

if (!defined('AIMOGEN_BULK_CONTENT_MAX_TOKENS')) {
    define('AIMOGEN_BULK_CONTENT_MAX_TOKENS', 4096);
}
if (!defined('AIMOGEN_BULK_DEFAULT_TEMPERATURE')) {
    define('AIMOGEN_BULK_DEFAULT_TEMPERATURE', 0.6);
}
if (!defined('AIMOGEN_BULK_DEFAULT_FREQUENCY_PENALTY')) {
    define('AIMOGEN_BULK_DEFAULT_FREQUENCY_PENALTY', 0.25);
}

function aimogen_bulk_natural_prose_enabled()
{
    $settings = get_option('aiomatic_Main_Settings', array());
    return is_array($settings) && isset($settings['bulk_natural_prose']) && $settings['bulk_natural_prose'] === 'on';
}

/**
 * Human-voice instructions prepended to bulk longform generation prompts.
 */
function aimogen_bulk_human_voice_guidelines()
{
    return 'Voice and format rules (apply to all output):
- Write like a knowledgeable human blogger, not an AI content mill.
- Prefer connected paragraphs over lists. Do NOT use bullet or numbered lists unless absolutely necessary (max one short list in the entire article, and only for a genuine comparison or checklist).
- Do not bold random phrases. Use <strong> sparingly — at most once per paragraph.
- Vary sentence length. Mix short and longer sentences.
- Never open with filler like "In today\'s fast-paced digital landscape", "When it comes to", "In the ever-evolving world of", or "It\'s no secret that".
- Avoid corporate AI words: leverage, streamline, robust, seamless, cutting-edge, game-changer, delve, tapestry, landscape (as metaphor), unlock, harness, elevate, empower, utilize (use "use" instead).
- Do not invent technical specs, algorithms, benchmarks, case studies, success stories, or statistics. Stick to accurate, general advice when specifics are unknown.
- Do not confuse the subject with unrelated product categories.';
}

/**
 * Prepend human-voice guidelines to longform bulk prompts (existing rules included).
 */
function aimogen_bulk_prepend_human_voice($prompt, $source = 'content')
{
    if ($source === 'editorPass') {
        return $prompt;
    }
    if (!aimogen_bulk_natural_prose_enabled() || !function_exists('aimogen_bulk_is_longform_source') || !aimogen_bulk_is_longform_source($source)) {
        return $prompt;
    }

    $guidelines = aimogen_bulk_human_voice_guidelines();
    if (stripos($prompt, 'Voice and format rules') !== false) {
        return $prompt;
    }

    return $guidelines . "\n\n" . $prompt;
}

function aimogen_bulk_editor_pass_enabled()
{
    $settings = get_option('aiomatic_Main_Settings', array());
    return is_array($settings) && isset($settings['bulk_editor_pass']) && $settings['bulk_editor_pass'] === 'on';
}

function aimogen_bulk_seo_meta_enabled()
{
    $settings = get_option('aiomatic_Main_Settings', array());
    return is_array($settings) && isset($settings['bulk_seo_meta']) && $settings['bulk_seo_meta'] === 'on';
}

function aimogen_bulk_preserve_prose()
{
    $settings = get_option('aiomatic_Main_Settings', array());
    return is_array($settings) && isset($settings['no_undetectibility_bulk']) && $settings['no_undetectibility_bulk'] === 'on';
}

/**
 * Default editor-pass prompt (can be overridden via aiomatic_Main_Settings[bulk_editor_prompt]).
 */
function aimogen_bulk_default_editor_prompt()
{
    return 'You are an experienced human editor rewriting a draft blog post so it reads naturally — not like AI-generated SEO content.

Article title: "%%title%%"
Primary topic/keyword: "%%topic%%"
Language: %%language%%

Draft HTML:
---
%%article_content%%
---

Rewrite and return ONLY the improved HTML (no commentary). Priorities:

1. HUMAN VOICE: Make it sound like a real person wrote it. Conversational but credible. Vary sentence rhythm. Remove robotic transitions ("Furthermore", "Additionally", "It is important to note").

2. FEWER LISTS: Convert most bullet/numbered lists into flowing paragraphs. The finished article should have at most ONE short list total, only if a list is genuinely the best format. Never stack multiple lists in a row.

3. LESS FORMATTING NOISE: Remove excessive <strong> tags. Keep bold only where a reader would naturally emphasize one phrase.

4. CUT AI CLICHÉS: Delete or rewrite openings like "In today\'s fast-paced digital landscape", "stands out as", "game-changer", "cutting-edge", "leverage", "streamline", "robust feature set", "seamless integration", and similar filler.

5. NO HALLUCINATIONS: Remove invented technical architecture, algorithms, benchmarks, case studies, success stories, or statistics. If a claim is speculative, soften to general advice or delete it. Stay accurate to what the topic actually is.

6. STRUCTURE: Keep a clear intro, logical H2 sections with short plain-language headings (not keyword-stuffed), and a natural conclusion. Remove repeated ideas across sections.

7. SEO (light touch): Mention the topic naturally in the intro and once in the body — no keyword stuffing.

8. Preserve images, iframes, tables, and links exactly.

Return the full rewritten article HTML only.';
}

/**
 * Run the final AI editor pass on assembled bulk article HTML.
 *
 * @param string $content Assembled article HTML.
 * @param array  $args    Context: title, topic, language, model, token, temperature, rule_id, etc.
 * @return string
 */
function aimogen_bulk_polish_article_content($content, $args = array())
{
    if (!aimogen_bulk_editor_pass_enabled()) {
        return $content;
    }

    $content = trim((string) $content);
    if ($content === '' || aiomatic_strlen(wp_strip_all_tags($content)) < 400) {
        return $content;
    }

    if (!function_exists('aiomatic_write_content')) {
        return $content;
    }

    $settings = get_option('aiomatic_Main_Settings', array());
    $title    = isset($args['title']) ? (string) $args['title'] : '';
    $topic    = isset($args['topic']) ? (string) $args['topic'] : $title;
    $language = isset($args['language']) && $args['language'] !== '' ? $args['language'] : 'English';

    $model = isset($args['model']) && $args['model'] !== '' ? $args['model'] : AIMOGEN_DEFAULT_MODEL;
    if (function_exists('aiomatic_get_default_model_name')) {
        $model = isset($args['model']) && $args['model'] !== '' ? $args['model'] : aiomatic_get_default_model_name($settings);
    }

    $token = isset($args['token']) ? $args['token'] : '';
    if ($token === '') {
        if (is_array($settings) && isset($settings['app_id']) && trim($settings['app_id']) !== '') {
            $appids = preg_split('/\r\n|\r|\n/', trim($settings['app_id']));
            $appids = array_filter(array_map('trim', $appids));
            if (!empty($appids)) {
                $token = $appids[array_rand($appids)];
            }
        }
    }
    if ($token === '') {
        return $content;
    }

    $prompt_template = aimogen_bulk_default_editor_prompt();
    if (is_array($settings) && !empty($settings['bulk_editor_prompt'])) {
        $prompt_template = $settings['bulk_editor_prompt'];
    }

    $prompt = str_replace(
        array('%%title%%', '%%topic%%', '%%language%%', '%%article_content%%'),
        array($title, $topic, $language, $content),
        $prompt_template
    );

    $temperature = isset($args['temperature']) && $args['temperature'] !== '' && is_numeric($args['temperature'])
        ? (float) $args['temperature']
        : 0.45;
    if ($temperature > 0.7) {
        $temperature = 0.45;
    }

    $top_p             = isset($args['top_p']) && $args['top_p'] !== '' ? $args['top_p'] : 0.9;
    $presence_penalty  = isset($args['presence_penalty']) && $args['presence_penalty'] !== '' ? $args['presence_penalty'] : 0;
    $frequency_penalty = isset($args['frequency_penalty']) && $args['frequency_penalty'] !== '' ? $args['frequency_penalty'] : 0.3;
    $max_tokens        = AIMOGEN_BULK_CONTENT_MAX_TOKENS;
    $global_prepend    = isset($args['global_prepend']) ? $args['global_prepend'] : '';
    $global_append     = isset($args['global_append']) ? $args['global_append'] : '';
    $assistant_id      = isset($args['assistant_id']) ? $args['assistant_id'] : '';
    $thread_id         = isset($args['thread_id']) ? $args['thread_id'] : '';
    $store_data        = isset($args['store_data']) ? $args['store_data'] : 'off';

    if (!empty($args['rule_id']) && function_exists('aiomatic_job_set_status_pending')) {
        aiomatic_job_set_status_pending($args['rule_id'], array('step' => 'Running final quality editor pass'));
    }

    $edited = aiomatic_write_content(
        $prompt,
        $model,
        $temperature,
        $top_p,
        $presence_penalty,
        $frequency_penalty,
        $max_tokens,
        $token,
        '',
        '',
        false,
        false,
        'editorPass',
        'user',
        $assistant_id,
        $thread_id,
        $store_data
    );

    if ($edited === false || trim($edited) === '') {
        if (isset($settings['enable_detailed_logging']) && $settings['enable_detailed_logging'] === 'on') {
            aiomatic_log_to_file('Bulk editor pass skipped: AI returned empty/false.');
        }
        return $content;
    }

    if (aiomatic_strlen(wp_strip_all_tags($edited)) < (int) (aiomatic_strlen(wp_strip_all_tags($content)) * 0.5)) {
        if (isset($settings['enable_detailed_logging']) && $settings['enable_detailed_logging'] === 'on') {
            aiomatic_log_to_file('Bulk editor pass rejected: output too short vs original.');
        }
        return $content;
    }

    return aimogen_bulk_scrub_ai_tells($edited);
}

/**
 * Light post-pass removal of common AI filler phrases.
 */
function aimogen_bulk_scrub_ai_tells($content)
{
    if (!aimogen_bulk_natural_prose_enabled() || trim((string) $content) === '') {
        return $content;
    }

    $replacements = array(
        '/\bIn today\'s fast-paced digital landscape,?\s*/i' => '',
        '/\bIn the ever-evolving world of [^,.]+,?\s*/i' => '',
        '/\bWhen it comes to [^,.]+,?\s*/i' => '',
        '/\bIt\'s (?:no secret|worth noting) that\s*/i' => '',
        '/\bstands out as a\b/i' => 'is a',
        '/\bleverage\b/i' => 'use',
        '/\butilize\b/i' => 'use',
        '/\bstreamline\b/i' => 'simplify',
        '/\brobust feature set\b/i' => 'useful features',
        '/\bseamless integration\b/i' => 'straightforward setup',
        '/\bcutting-edge\b/i' => 'modern',
        '/\bgame-changer\b/i' => 'useful tool',
        '/\bFurthermore,\s*/i' => '',
        '/\bAdditionally,\s*/i' => '',
        '/\bIt is important to note that\s*/i' => '',
    );

    foreach ($replacements as $pattern => $replacement) {
        $content = preg_replace($pattern, $replacement, $content);
    }

    return $content;
}

/**
 * Save SEO plugin meta after bulk post insert.
 */
function aimogen_bulk_save_seo_for_post($post_id, $title = '', $excerpt = '', $focus_keyword = '')
{
    if (!aimogen_bulk_seo_meta_enabled() || empty($post_id) || !function_exists('aiomatic_save_seo_description')) {
        return;
    }

    $meta_desc = trim(wp_strip_all_tags((string) $excerpt));
    if ($meta_desc === '') {
        $content = get_post_field('post_content', $post_id);
        if (is_string($content) && $content !== '') {
            $meta_desc = wp_trim_words(wp_strip_all_tags($content), 28, '…');
        }
    }
    if (function_exists('mb_strlen') && function_exists('mb_substr') && mb_strlen($meta_desc) > 160) {
        $meta_desc = mb_substr($meta_desc, 0, 157) . '…';
    } elseif (strlen($meta_desc) > 160) {
        $meta_desc = substr($meta_desc, 0, 157) . '…';
    }

    $focus = trim((string) $focus_keyword);
    if ($focus === '') {
        $focus = trim((string) $title);
    }

    aiomatic_save_seo_description((int) $post_id, $meta_desc, $focus);
}

/**
 * Post-insert hook wrapper for bulk rules.
 */
function aimogen_bulk_on_post_created($post_id, $title = '', $excerpt = '', $topic = '')
{
    aimogen_bulk_save_seo_for_post($post_id, $title, $excerpt, $topic !== '' ? $topic : $title);
}

/**
 * Final prose cleanup — skip grammar-breaking replacements when quality mode is on.
 */
function aimogen_bulk_finalize_prose($content)
{
    $content = str_replace('’', '\'', (string) $content);
    $content = str_replace('—', '-', $content);

    if (!aimogen_bulk_preserve_prose()) {
        $content = str_replace('genuinely ', '', $content);
        $content = str_replace(', and', 'and', $content);
        $content = str_replace(', or', 'or', $content);
    }

    return aimogen_bulk_scrub_ai_tells($content);
}

/**
 * Whether a write_content source should use the higher bulk token ceiling.
 */
function aimogen_bulk_is_longform_source($source)
{
    $source = (string) $source;
    if ($source === 'editorPass') {
        return true;
    }
    $longform = array('intro', 'excerpt', 'qa', 'outro', 'content');
    foreach ($longform as $needle) {
        if (stripos($source, $needle) !== false) {
            return true;
        }
    }
    return false;
}

/**
 * Apply generation defaults for empty rule-level sampling params.
 */
function aimogen_bulk_resolve_temperature($temperature)
{
    if ($temperature === '' || $temperature === null || !is_numeric($temperature)) {
        return AIMOGEN_BULK_DEFAULT_TEMPERATURE;
    }
    return (float) $temperature;
}

function aimogen_bulk_resolve_frequency_penalty($frequency_penalty)
{
    if ($frequency_penalty === '' || $frequency_penalty === null || !is_numeric($frequency_penalty)) {
        return AIMOGEN_BULK_DEFAULT_FREQUENCY_PENALTY;
    }
    return (float) $frequency_penalty;
}
