#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Rewrite 3 functions - fixed version without surrogate pairs.
Uses actual emoji characters instead of \\ud83d\\udcc2 escapes.
"""

import re

filepath = r'D:\AI-Ad-Agent\portal\portal.html'

with open(filepath, 'r', encoding='utf-8') as f:
    content = f.read()

# Helper: replace JS surrogate pairs with actual emoji
def fix_emoji(s):
    return s.replace('\\ud83d\\udcc2', '\U0001F4C2')  # folder
     .replace('\\ud83d\\udccb', '\U0001F4CB')          # clipboard
     .replace('\\ud83d\\udc41\\ufe0f', '\U0001F441\uFE0F')  # eye
     .replace('\\ud83e\\udd16', '\U0001F916')           # robot
     .replace('\\u2b07\\ufe0f', '\u2B07\uFE0F')        # down arrow
     .replace('\\u2022', '\u2022')                      # bullet
     .replace('\\u00b7', '\u00B7')                      # middle dot

results = []

# ============================================================
# Function 1: handleMaterialSearch
# ============================================================
pattern1 = r'async function handleMaterialSearch\(\) \{.*?// ====== \u6848\u4f8b\u63a8\u8350 ======'
match1 = re.search(pattern1, content, re.DOTALL)
if match1:
    new_func1 = fix_emoji('''async function handleMaterialSearch() {
  if (!requireLogin()) return;
  const prompt = document.getElementById('material-search-prompt').value.trim();
  if (!prompt) { showToast('请输入提示词/需求描述'); return; }

  const industry = document.getElementById('material-search-industry').value;
  const materialType = document.getElementById('material-search-type').value;
  const color = document.getElementById('material-search-color').value;
  const otherReq = document.getElementById('material-search-other').value.trim();

  document.getElementById('material-search-loading').style.display = 'block';
  document.getElementById('material-search-results-card').style.display = 'none';
  document.getElementById('material-search-materials-card').style.display = 'none';
  document.getElementById('material-search-btn').disabled = true;

  try {
    // === Step 1: Search KB (80% main content) ===
    let dbMaterials = [];
    let dbCopies = [];
    try {
      const searchParams = new URLSearchParams();
      searchParams.append('q', prompt + ' ' + industry);
      if (materialType === '图片') searchParams.append('category', 'material');
      const kbResp = await fetch(`${PORTAL_URL}/api/knowledge/search?${searchParams.toString()}`, {
        headers: { 'Authorization': `Bearer ${authToken}` }
      });
      const kbData = await kbResp.json();
      if (kbData.success && kbData.files) {
        dbMaterials = kbData.files;
        dbCopies = kbData.files.filter(f => f.metadata && f.metadata.trim());
      }
    } catch(e) { console.error('Knowledge search error:', e); }

    const copyListEl = document.getElementById('material-search-copy-list');
    copyListEl.innerHTML = '';
    const hasKB = dbCopies.length > 0;

    // === Step 2: KB content occupies 80% ===
    if (hasKB) {
      dbCopies.slice(0, 8).forEach((f, i) => {
        const div = document.createElement('div');
        div.className = 'copy-card';
        div.style.cssText = 'background:#f0f9ff;border:1px solid #bae6fd;border-radius:8px;padding:14px 16px;margin-bottom:10px;';
        const metaText = f.metadata.substring(0, 500);
        const metaSuffix = f.metadata.length > 500 ? '...' : '';
        div.innerHTML = '<div style="font-size:11px;color:#0369a1;font-weight:600;margin-bottom:4px;">\\ud83d\\udcc2 知识库文案 ' + (i+1) + ' \\u00b7 ' + f.filename + '</div>' +
          '<div style="font-size:14px;line-height:1.6;">' + metaText + metaSuffix + '</div>' +
          '<div style="margin-top:8px;display:flex;gap:8px;">' +
          '<button style="font-size:12px;padding:4px 10px;border-radius:6px;border:1px solid var(--border);background:#fff;cursor:pointer;" onclick="navigator.clipboard.writeText(this.closest(\\'.copy-card\\').innerText)">\\ud83d\\udccb 复制</button>' +
          '<button style="font-size:12px;padding:4px 10px;border-radius:6px;border:1px solid var(--border);background:#fff;cursor:pointer;" onclick="previewKFile(' + f.id + ')">\\ud83d\\udc41\\ufe0f 预览原文件</button>' +
          '</div>';
        copyListEl.appendChild(div);
      });
    }

    // === Step 3: AI analysis occupies 20% ===
    if (hasKB) {
      const kbSummary = dbCopies.slice(0, 5).map(f => f.metadata.substring(0, 200)).join('\\n---\\n');
      const aiPrompt = '你是资深广告素材优化师。以下是知识库中的素材文案，请基于这些内容做优化分析（不要重新生成文案，只做分析）：\\n\\n需求：' + prompt + '\\n行业：' + (industry || '不限') + '\\n\\n知识库文案内容：\\n' + kbSummary + '\\n\\n请输出：\\n1. 知识库文案亮点分析（2-3点）\\n2. 优化建议（2-3点，如何提升转化率）\\n3. 推荐使用场景\\n\\n控制在200字以内。';

      let aiSuggestion = '';
      try {
        const resp = await fetch(`${PORTAL_URL}/api/ollama/api/generate`, {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({model: DEFAULT_MODEL, prompt: aiPrompt, stream: false, think: false})
        });
        const data = await resp.json();
        aiSuggestion = data.response || data.message || '';
      } catch(e) { console.error('AI analysis error:', e); }

      if (aiSuggestion) {
        const aiDiv = document.createElement('div');
        aiDiv.className = 'copy-card';
        aiDiv.style.cssText = 'background:#fef3c7;border:1px solid #fbbf24;border-radius:8px;padding:14px 16px;margin-bottom:10px;';
        const safeText = aiSuggestion.replace(/</g,'&lt;').replace(/\\n/g,'<br>');
        aiDiv.innerHTML = '<div style="font-size:11px;color:#92400e;font-weight:600;margin-bottom:6px;">\\ud83e\\udd16 AI优化分析（基于知识库内容，占20%）</div>' +
          '<div style="font-size:13px;line-height:1.6;color:#78350f;">' + safeText + '</div>';
        copyListEl.appendChild(aiDiv);
      }
    } else {
      // === KB empty: 100% AI generation ===
      const copyPrompt = '你是资深广告文案策划。根据以下需求生成3条广告素材文案（每条100字以内）：\\n需求：' + prompt + '\\n行业：' + (industry || '不限') + '\\n素材类型：' + (materialType || '不限') + '\\n主色调：' + (color || '不限') + '\\n其他需求：' + (otherReq || '无') + '\\n\\n请按JSON格式返回：[{"title":"标题","body":"正文","style":"风格"}]\\n只返回JSON。';

      let copyList = [];
      try {
        const resp = await fetch(`${PORTAL_URL}/api/ollama/api/generate`, {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({model: DEFAULT_MODEL, prompt: copyPrompt, stream: false, think: false})
        });
        const data = await resp.json();
        const text = data.response || data.message || '';
        const jsonMatch = text.match(/\\[.*\\]/s);
        if (jsonMatch) copyList = JSON.parse(jsonMatch[0]);
      } catch(e) { console.error('Ollama error:', e); }

      if (!copyList || copyList.length === 0) {
        copyList = [{title: '参考方案', body: prompt, style: '基础'}];
      }

      copyList.forEach((item, i) => {
        const div = document.createElement('div');
        div.className = 'copy-card';
        div.style.cssText = 'background:#fef3c7;border:1px solid #fbbf24;border-radius:8px;padding:14px 16px;margin-bottom:10px;';
        div.innerHTML = '<div style="font-size:11px;color:#92400e;font-weight:600;margin-bottom:4px;">\\ud83e\\udd16 AI生成文案 ' + (i+1) + ' \\u00b7 ' + (item.style || '通用') + '</div>' +
          '<div style="font-size:14px;line-height:1.6;"><strong>' + (item.title || '') + '</strong><br>' + (item.body || '') + '</div>' +
          '<div style="margin-top:8px;"><button style="font-size:12px;padding:4px 10px;border-radius:6px;border:1px solid var(--border);background:#fff;cursor:pointer;" onclick="navigator.clipboard.writeText(this.closest(\\'.copy-card\\').innerText)">\\ud83d\\udccb 复制</button></div>';
        copyListEl.appendChild(div);
      });
    }

    document.getElementById('material-search-results-card').style.display = '';

    // === Step 4: Display KB material files ===
    const grid = document.getElementById('material-search-material-grid');
    const empty = document.getElementById('material-search-material-empty');
    grid.innerHTML = '';
    if (dbMaterials.length === 0) {
      empty.style.display = '';
    } else {
      empty.style.display = 'none';
      dbMaterials.forEach(m => {
        const div = document.createElement('div');
        div.className = 'material-card';
        div.style.cssText = 'border:1px solid var(--border);border-radius:10px;overflow:hidden;padding:12px;';
        let metaHtml = m.metadata ? '<div style="font-size:12px;margin-top:6px;color:var(--text);">' + m.metadata.substring(0, 100) + '</div>' : '';
        div.innerHTML = '<div style="font-size:14px;font-weight:500;margin-bottom:4px;">' + (m.filename || '素材') + '</div>' +
          '<div style="font-size:12px;color:var(--text-secondary);">分类：' + (m.category || '未分类') + ' \\u00b7 ' + (m.upload_time || '') + '</div>' +
          metaHtml +
          '<div style="margin-top:8px;display:flex;gap:6px;">' +
          '<button style="font-size:11px;padding:3px 8px;border-radius:6px;border:1px solid var(--border);background:#fff;cursor:pointer;" onclick="previewKFile(' + m.id + ')">\\ud83d\\udc41\\ufe0f 预览</button>' +
          '<button style="font-size:11px;padding:3px 8px;border-radius:6px;border:1px solid var(--border);background:#fff;cursor:pointer;" onclick="downloadKFile(' + m.id + ')">\\u2b07\\ufe0f 下载</button>' +
          '</div>';
        grid.appendChild(div);
      });
    }
    document.getElementById('material-search-materials-card').style.display = '';

    saveRecord('material_search', '素材检索: ' + prompt.substring(0, 50),
      '提示词: ' + prompt + '<br>行业: ' + industry + '<br>知识库文案: ' + dbCopies.length + '条<br>知识库素材: ' + dbMaterials.length + '条<br>AI占比: ' + (hasKB ? '20%分析' : '100%生成'),
      { prompt, industry, material_type: materialType });

  } catch(e) {
    showToast('检索失败：' + e.message, 'error');
  } finally {
    document.getElementById('material-search-loading').style.display = 'none';
    document.getElementById('material-search-btn').disabled = false;
  }
}

// ====== 案例推荐 ======''')

    content = content[:match1.start()] + new_func1 + content[match1.end():]
    results.append("[OK] handleMaterialSearch replaced")
else:
    results.append("[SKIP] handleMaterialSearch not found")

# Save intermediate to check
with open(filepath, 'w', encoding='utf-8') as f:
    f.write(content)

for r in results:
    print(r)
print("Step 1 done (material search)")
