<?php
class AITitleGenerator {
    private $gpt;
    private $db;
    
    public function __construct($database) {
        $this->gpt = new GPTAPI();
        $this->db = $database;
    }
    
    public function generateTitles($context) {
        $prompt = $this->buildTitlePrompt($context);
        
        try {
            $response = $this->gpt->generateContent($prompt, [
                'max_tokens' => 500,
                'temperature' => 0.8
            ]);
            
            return $this->parseTitleResponse($response);
        } catch (Exception $e) {
            // Fallback to template-based generation
            return $this->generateTemplateTitles($context);
        }
    }
    
    public function analyzeTitle($title, $keywords = '') {
        $prompt = "請分析以下文章標題的SEO效果和吸引力：\n\n";
        $prompt .= "標題：{$title}\n";
        
        if (!empty($keywords)) {
            $prompt .= "目標關鍵字：{$keywords}\n";
        }
        
        $prompt .= "\n請從以下角度分析：\n";
        $prompt .= "1. SEO優化程度（關鍵字密度、位置）\n";
        $prompt .= "2. 吸引力（是否吸引點擊）\n";
        $prompt .= "3. 長度適宜性（建議50-60字元）\n";
        $prompt .= "4. 情感觸發（是否引起情感共鳴）\n";
        $prompt .= "5. 改進建議\n\n";
        $prompt .= "請以JSON格式回應：\n";
        $prompt .= "{\n";
        $prompt .= "  \"seo_score\": 分數(1-10),\n";
        $prompt .= "  \"attractiveness_score\": 分數(1-10),\n";
        $prompt .= "  \"length_score\": 分數(1-10),\n";
        $prompt .= "  \"emotion_score\": 分數(1-10),\n";
        $prompt .= "  \"overall_score\": 總分(1-10),\n";
        $prompt .= "  \"analysis\": \"詳細分析\",\n";
        $prompt .= "  \"suggestions\": [\"建議1\", \"建議2\", \"建議3\"]\n";
        $prompt .= "}";
        
        try {
            $response = $this->gpt->generateContent($prompt, [
                'max_tokens' => 300,
                'temperature' => 0.3
            ]);
            
            return $this->parseAnalysisResponse($response);
        } catch (Exception $e) {
            return $this->getDefaultAnalysis($title, $keywords);
        }
    }
    
    public function optimizeTitle($title, $keywords = '', $target_length = 60, $tone = 'professional') {
        $prompt = "請優化以下文章標題：\n\n";
        $prompt .= "原始標題：{$title}\n";
        
        if (!empty($keywords)) {
            $prompt .= "目標關鍵字：{$keywords}\n";
        }
        
        $prompt .= "目標長度：{$target_length}字元\n";
        $prompt .= "語調：{$tone}\n\n";
        $prompt .= "優化要求：\n";
        $prompt .= "1. 保持原意不變\n";
        $prompt .= "2. 優化SEO效果\n";
        $prompt .= "3. 增強吸引力\n";
        $prompt .= "4. 控制長度在目標範圍內\n";
        $prompt .= "5. 符合指定語調\n\n";
        $prompt .= "請提供3個優化版本，以JSON格式回應：\n";
        $prompt .= "{\n";
        $prompt .= "  \"optimized_titles\": [\n";
        $prompt .= "    {\n";
        $prompt .= "      \"title\": \"優化標題1\",\n";
        $prompt .= "      \"reason\": \"優化原因\"\n";
        $prompt .= "    },\n";
        $prompt .= "    {\n";
        $prompt .= "      \"title\": \"優化標題2\",\n";
        $prompt .= "      \"reason\": \"優化原因\"\n";
        $prompt .= "    },\n";
        $prompt .= "    {\n";
        $prompt .= "      \"title\": \"優化標題3\",\n";
        $prompt .= "      \"reason\": \"優化原因\"\n";
        $prompt .= "    }\n";
        $prompt .= "  ]\n";
        $prompt .= "}";
        
        try {
            $response = $this->gpt->generateContent($prompt, [
                'max_tokens' => 400,
                'temperature' => 0.7
            ]);
            
            return $this->parseOptimizationResponse($response);
        } catch (Exception $e) {
            return $this->getDefaultOptimization($title, $keywords, $target_length);
        }
    }
    
    private function buildTitlePrompt($context) {
        $prompt = "請為以下內容計畫生成{$context['count']}個吸引人的文章標題：\n\n";
        $prompt .= "計畫標題：{$context['plan_title']}\n";
        
        if (!empty($context['brand_name'])) {
            $prompt .= "品牌名稱：{$context['brand_name']}\n";
        }
        
        if (!empty($context['target_keywords'])) {
            $prompt .= "目標關鍵字：{$context['target_keywords']}\n";
        }
        
        $prompt .= "內容類型：{$context['content_type']}\n";
        $prompt .= "語調：{$context['tone']}\n\n";
        
        $prompt .= "標題要求：\n";
        $prompt .= "1. 長度控制在50-60字元內\n";
        $prompt .= "2. 包含主要關鍵字\n";
        $prompt .= "3. 具有吸引力和點擊誘因\n";
        $prompt .= "4. 符合{$context['tone']}語調\n";
        $prompt .= "5. 適合{$context['content_type']}內容類型\n\n";
        
        $prompt .= "請以JSON格式回應：\n";
        $prompt .= "{\n";
        $prompt .= "  \"titles\": [\n";
        $prompt .= "    {\n";
        $prompt .= "      \"title\": \"標題1\",\n";
        $prompt .= "      \"type\": \"標題類型\",\n";
        $prompt .= "      \"reason\": \"推薦原因\"\n";
        $prompt .= "    },\n";
        $prompt .= "    {\n";
        $prompt .= "      \"title\": \"標題2\",\n";
        $prompt .= "      \"type\": \"標題類型\",\n";
        $prompt .= "      \"reason\": \"推薦原因\"\n";
        $prompt .= "    }\n";
        $prompt .= "  ]\n";
        $prompt .= "}";
        
        return $prompt;
    }
    
    private function parseTitleResponse($response) {
        try {
            $data = json_decode($response, true);
            if (isset($data['titles']) && is_array($data['titles'])) {
                return $data['titles'];
            }
        } catch (Exception $e) {
            // Fallback parsing
        }
        
        // Fallback: extract titles from text response
        $titles = [];
        $lines = explode("\n", $response);
        foreach ($lines as $line) {
            $line = trim($line);
            if (strlen($line) > 10 && strlen($line) < 100) {
                $titles[] = [
                    'title' => $line,
                    'type' => 'AI生成',
                    'reason' => 'AI智能生成'
                ];
            }
        }
        
        return array_slice($titles, 0, 5);
    }
    
    private function parseAnalysisResponse($response) {
        try {
            $data = json_decode($response, true);
            if (isset($data['seo_score'])) {
                return $data;
            }
        } catch (Exception $e) {
            // Fallback parsing
        }
        
        return $this->getDefaultAnalysis('', '');
    }
    
    private function parseOptimizationResponse($response) {
        try {
            $data = json_decode($response, true);
            if (isset($data['optimized_titles']) && is_array($data['optimized_titles'])) {
                return $data;
            }
        } catch (Exception $e) {
            // Fallback parsing
        }
        
        return $this->getDefaultOptimization('', '', 60);
    }
    
    private function generateTemplateTitles($context) {
        $templates = [
            "{$context['plan_title']}：完整指南",
            "如何{$context['plan_title']}？專家分享",
            "{$context['plan_title']}的最佳實踐",
            "{$context['plan_title']}：從入門到精通",
            "{$context['plan_title']}的5個關鍵要素"
        ];
        
        $titles = [];
        foreach ($templates as $template) {
            $titles[] = [
                'title' => $template,
                'type' => '模板生成',
                'reason' => '基於模板的智能生成'
            ];
        }
        
        return array_slice($titles, 0, $context['count']);
    }
    
    private function getDefaultAnalysis($title, $keywords) {
        $length = strlen($title);
        $length_score = $length >= 50 && $length <= 60 ? 10 : ($length < 50 ? 8 : 6);
        
        return [
            'seo_score' => 7,
            'attractiveness_score' => 7,
            'length_score' => $length_score,
            'emotion_score' => 6,
            'overall_score' => 7,
            'analysis' => '標題分析功能暫時不可用，請稍後再試。',
            'suggestions' => [
                '確保標題長度在50-60字元內',
                '包含主要關鍵字',
                '增加情感觸發詞',
                '使用數字或問句增加吸引力'
            ]
        ];
    }
    
    private function getDefaultOptimization($title, $keywords, $target_length) {
        return [
            'optimized_titles' => [
                [
                    'title' => $title,
                    'reason' => '原始標題'
                ],
                [
                    'title' => $title . '：完整指南',
                    'reason' => '增加指南性描述'
                ],
                [
                    'title' => '如何' . $title . '？',
                    'reason' => '轉換為問句形式'
                ]
            ]
        ];
    }
}
?>
