<?php

namespace HaoZiTeam\AIPost\Service\Settings\Traits;

use HaoZiTeam\AIPost\Service\Features\Logger;

defined('ABSPATH') || exit;

trait TraitPromptPresets
{
    // 读取并解析写作指令预设
    private function get_preset_instructions(): array
    {
        try {
            $service_dir = dirname(__FILE__, 3); // .../Service
            $file = rtrim($service_dir, "/\\") . DIRECTORY_SEPARATOR . 'Features' . DIRECTORY_SEPARATOR . 'AIcommand.txt';
            $content = '';
            if (@file_exists($file)) {
                $raw = @file_get_contents($file);
                if ($raw !== false) {
                    $enc = function_exists('mb_detect_encoding') ? @mb_detect_encoding($raw, ['UTF-8','GBK','GB2312','BIG5','ISO-8859-1'], true) : false;
                    if ($enc && strtoupper($enc) !== 'UTF-8') {
                        if (function_exists('mb_convert_encoding')) {
                            $content = @mb_convert_encoding($raw, 'UTF-8', $enc);
                        } elseif (function_exists('iconv')) {
                            $content = @iconv($enc, 'UTF-8//IGNORE', $raw);
                        }
                    }
                    if ($content === '' || $content === null) { $content = $raw; }
                }
            }
            $content = (string)($content ?? '');

            $map = [
                'personify' => '',
                'professional' => '',
                'humor' => '',
                'google_seo' => ''
            ];
            if ($content !== '') {
                $t1 = '拟人化风格指令';
                $t2 = '专业化写作指令';
                $t3 = '幽默化写作指令';
                $t4 = 'google seo指令';
                $p1 = mb_strpos($content, $t1, 0, 'UTF-8');
                $p2 = mb_strpos($content, $t2, 0, 'UTF-8');
                $p3 = mb_strpos($content, $t3, 0, 'UTF-8');
                $p4 = mb_strpos($content, $t4, 0, 'UTF-8');

                $len = mb_strlen($content, 'UTF-8');
                $slice = function($start, $end) use ($content, $len) {
                    if ($start === false) { return ''; }
                    $segmentStart = $start; // 标题行一起切出，后续去掉首行
                    return trim(mb_substr($content, $segmentStart, ($end !== false ? ($end - $segmentStart) : ($len - $segmentStart)), 'UTF-8'));
                };
                $strip_heading = function($text) use ($t1, $t2, $t3, $t4){
                    $text = ltrim((string)$text);
                    if (preg_match('/^\s*##\s*.+\r?\n/i', $text, $m)) {
                        $text = substr($text, strlen($m[0]));
                        $text = ltrim($text);
                    }
                    $lines = preg_split("/\r?\n/", $text);
                    if (is_array($lines) && count($lines) > 0) {
                        $idx = 0;
                        while ($idx < count($lines) && trim($lines[$idx]) === '') { $idx++; }
                        if ($idx < count($lines)) {
                            $first = trim($lines[$idx]);
                            $norm = ltrim($first, "# ");
                            $titles = [$t1, $t2, $t3, $t4];
                            foreach ($titles as $title) {
                                if ($title && mb_strpos($norm, $title, 0, 'UTF-8') === 0) {
                                    array_splice($lines, $idx, 1);
                                    break;
                                }
                            }
                        }
                        $text = trim(implode("\n", $lines));
                    }
                    return $text;
                };
                $cleanup_tail = function($text){
                    $lines = preg_split("/\r?\n/", (string)$text);
                    if (!is_array($lines)) { return trim((string)$text); }
                    while (!empty($lines)) {
                        $last = trim((string)end($lines));
                        if ($last === '' || preg_match('/^#+$/', $last)) { array_pop($lines); continue; }
                        if (preg_match('/^##\s*/', $last)) { array_pop($lines); continue; }
                        break;
                    }
                    return trim(implode("\n", $lines));
                };

                if ($p1 !== false) {
                    $end = false; foreach ([$p2, $p3, $p4] as $pp) { if ($pp !== false && ($end === false || $pp < $end)) { $end = $pp; } }
                    $map['personify'] = $cleanup_tail($strip_heading($slice($p1, $end)));
                }
                if ($p2 !== false) {
                    $end = false; foreach ([$p3, $p4] as $pp) { if ($pp !== false && ($end === false || $pp < $end)) { $end = $pp; } }
                    $map['professional'] = $cleanup_tail($strip_heading($slice($p2, $end)));
                }
                if ($p3 !== false) {
                    $end = ($p4 !== false && $p4 > $p3) ? $p4 : false;
                    $map['humor'] = $cleanup_tail($strip_heading($slice($p3, $end)));
                }
                if ($p4 !== false) { $map['google_seo'] = $cleanup_tail($strip_heading($slice($p4, false))); }
            }

            $defaults = [
                'personify' => "请以更贴近人类口语、具备情感共鸣与生动比喻的方式来写作，保持结构清晰，避免口水话与过度拟人。",
                'professional' => "请以专业作者风格撰写，使用准确术语与清晰逻辑，给出步骤分层与要点列表，结论明确，避免主观夸大。",
                'humor' => "请以轻松幽默且不低俗的笔调写作，使用恰当的段子/反转/类比，保持信息有效与逻辑性。",
                'google_seo' => "请依据E-E-A-T与用户检索意图，以说人话、可执行的步骤，输出兼顾可读性与搜索友好的文章框架。"
            ];
            foreach ($defaults as $k => $v) {
                if (!isset($map[$k]) || trim((string)$map[$k]) === '') { $map[$k] = $v; }
            }
            return $map;
        } catch (\Throwable $e) {
            Logger::warning('Failed to load writing presets: ' . $e->getMessage(), 'Setting');
            return [
                'personify' => '请以更贴近人类口语、具备情感共鸣与生动比喻的方式来写作，保持结构清晰。',
                'professional' => '请以专业作者风格撰写，使用准确术语与清晰逻辑，给出步骤分层与要点列表。',
                'humor' => '请以轻松幽默且不低俗的笔调写作，使用恰当的段子/反转/类比，保持信息有效。',
                'google_seo' => '请依据E-E-A-T与用户检索意图，以说人话、可执行的步骤，输出兼顾可读性与搜索友好的文章框架。',
            ];
        }
    }

    // 渲染系统指令字段下方的三枚快捷按钮与点击逻辑
    private function render_system_prompt_presets(): string
    {
        try {
            $presets = $this->get_preset_instructions();
            $json = function_exists('wp_json_encode') ? wp_json_encode($presets, JSON_UNESCAPED_UNICODE) : json_encode($presets, JSON_UNESCAPED_UNICODE);
            ob_start();
            ?>
            <div class="aipost-preset-box" style="margin-top:8px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                <button type="button" class="button aipost-instruction-btn" data-type="personify">拟人化风格</button>
                <button type="button" class="button aipost-instruction-btn" data-type="professional">专业化写作</button>
                <button type="button" class="button aipost-instruction-btn" data-type="humor">幽默化写作</button>
                <button type="button" class="button aipost-instruction-btn" data-type="google_seo">Google SEO 指令</button>
                <span style="color:#777;line-height:28px;white-space:nowrap;">一键填入常用写作指令</span>
                <button type="button" class="button button-secondary aipost-instruction-btn-custom">自定义指令</button>
            </div>
            <script>(function(){
                try { window.AIPostPresets = <?php echo $json ?: '{}'; ?>; } catch(e) { window.AIPostPresets = {}; }
                function findTextarea(el){
                    var box = el.closest('.cgps-field');
                    if (box) {
                        var ta = box.querySelector('textarea');
                        if (ta) return ta;
                    }
                    var p = el; var limit = 4;
                    while(p && limit-- > 0){
                        var t = p.querySelector ? p.querySelector('textarea') : null;
                        if (t) return t; p = p.parentElement;
                    }
                    return null;
                }
                document.addEventListener('click', function(ev){
                    var btn = ev.target.closest('.aipost-instruction-btn');
                    if (btn) {
                        var type = btn.getAttribute('data-type') || '';
                        var text = (window.AIPostPresets && window.AIPostPresets[type]) ? String(window.AIPostPresets[type]) : '';
                        var ta = findTextarea(btn);
                        if (!ta) { alert('未找到 AI 设定文本框'); return; }
                        try {
                            ta.value = text;
                            if (typeof jQuery !== 'undefined') { jQuery(ta).trigger('change'); }
                        } catch(e) {}
                        return;
                    }

                    var customBtn = ev.target.closest('.aipost-instruction-btn-custom');
                    if (customBtn) {
                        var ta2 = findTextarea(customBtn);
                        if (!ta2) { alert('未找到 AI 设定文本框'); return; }
                        try {
                            ta2.value = '';
                            if (typeof jQuery !== 'undefined') { jQuery(ta2).trigger('change'); }
                        } catch(e) {}
                        return;
                    }
                }, false);
            })();</script>
            <?php
            return (string)ob_get_clean();
        } catch (\Throwable $e) {
            return '';
        }
    }
}
