#!/usr/bin/env python3
# fix_km_folder_view.py - 将知识库管理改为文件夹视图
import re

HTML = r"D:\AI-Ad-Agent\portal\portal.html"

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

# 1. 替换文件列表区域为文件夹视图
old_list = '''          <div style="margin-top:24px;">
            <div style="font-size:16px;font-weight:600;margin-bottom:16px;">📋 文件列表</div>
            <div class="form-row" style="display:flex;gap:12px;margin-bottom:16px;">
              <select id="km-filter-category" onchange="loadKFiles()" style="padding:8px 12px;border:1px solid var(--border);border-radius:8px;">
                <option value="">全部分类</option>
                <option value="material">素材类</option>
                <option value="case">案例类</option>
                <option value="knowledge">知识点</option>
              </select>
              <input type="text" id="km-search-input" placeholder="搜索文件名..." oninput="loadKFiles()" style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:8px;">
              <button class="btn btn-sm" onclick="loadKFiles()">🔍 搜索</button>
            </div>
            <div id="km-file-list" class="file-list" style="display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:16px;">
              <div class="empty" style="text-align:center;padding:60px 20px;color:var(--text-secondary);grid-column:1/-1;"><div style="font-size:64px;margin-bottom:16px;">📂</div>暂无文件，请上传</div>
            </div>
          </div>'''

new_list = '''          <!-- 文件夹视图 -->
          <div id="km-folder-view" style="margin-top:24px;">
            <div style="font-size:16px;font-weight:600;margin-bottom:16px;">📁 知识库文件夹</div>
            <div id="km-folder-list" class="folder-grid" style="display:grid;grid-template-columns:repeat(auto-fill, minmax(220px, 1fr));gap:20px;">
              <div class="empty" style="text-align:center;padding:60px 20px;color:var(--text-secondary);grid-column:1/-1;"><div style="font-size:64px;margin-bottom:16px;">📂</div>加载中...</div>
            </div>
          </div>
          
          <!-- 文件列表视图（点击文件夹后显示） -->
          <div id="km-file-view" style="margin-top:24px;display:none;">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
              <button class="btn btn-sm btn-secondary" onclick="showKFolderView()">← 返回文件夹</button>
              <div style="font-size:16px;font-weight:600;" id="km-current-folder-title">素材</div>
              <div style="margin-left:auto;">
                <input type="text" id="km-search-input" placeholder="搜索文件名..." oninput="filterKFiles()" style="padding:8px 12px;border:1px solid var(--border);border-radius:8px;width:200px;">
              </div>
            </div>
            <div id="km-file-list" class="file-list" style="display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:16px;">
              <div class="empty" style="text-align:center;padding:60px 20px;color:var(--text-secondary);grid-column:1/-1;"><div style="font-size:64px;margin-bottom:16px;">📂</div>暂无文件</div>
            </div>
          </div>'''

if old_list in content:
    content = content.replace(old_list, new_list)
    print("[OK] 文件夹视图HTML已替换")
else:
    print("[WARN] 未找到文件列表区域，尝试手动查找...")
    # 备用：查找特征字符串
    if 'km-filter-category' in content:
        print("[INFO] 找到 km-filter-category，但格式不匹配，跳过HTML替换")
        print("[INFO] 将只更新JS函数")

# 2. 在 </script> 前添加文件夹视图JS函数
js_functions = '''
// ===== 知识库文件夹视图 =====

// 文件夹定义
const KM_FOLDERS = [
  { id: 'material',   name: '素材',   icon: '🖼️', desc: '图片、视频等广告素材', color: '#6366f1' },
  { id: 'case',       name: '案例',   icon: '📊', desc: '优质广告案例分析',   color: '#f59e0b' },
  { id: 'knowledge',  name: '知识点', icon: '📚', desc: '文案、流程等知识内容', color: '#10b981' },
];

let _kmCurrentCategory = null; // 当前打开的文件夹分类
let _kmAllFiles = [];         // 缓存当前文件列表

// 显示文件夹视图
async function showKFolderView() {
  document.getElementById('km-folder-view').style.display = '';
  document.getElementById('km-file-view').style.display = 'none';
  _kmCurrentCategory = null;
  _kmAllFiles = [];
  await loadKFolderView();
}

// 加载文件夹视图（显示3个文件夹+文件数量）
async function loadKFolderView() {
  const container = document.getElementById('km-folder-list');
  container.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-secondary);grid-column:1/-1;">加载中...</div>';
  
  try {
    const resp = await fetch(`${KM_API}/list`, {
      headers: { 'Authorization': `Bearer ${authToken}` }
    });
    const data = await resp.json();
    const files = data.files || [];
    
    // 统计每个分类的文件数量
    const counts = {};
    KM_FOLDERS.forEach(f => counts[f.id] = 0);
    files.forEach(f => {
      if (counts[f.category] !== undefined) counts[f.category]++;
    });
    
    // 渲染文件夹卡片
    container.innerHTML = KM_FOLDERS.map(f => {
      const count = counts[f.id];
      return `
        <div class="folder-card" onclick="openKFolder('${f.id}')" 
             style="background:white;border:1px solid var(--border);border-radius:16px;padding:28px 24px;cursor:pointer;transition:all 0.2s;text-align:center;"
             onmouseover="this.style.borderColor='${f.color}';this.style.boxShadow='0 8px 25px rgba(0,0,0,0.1)';this.style.transform='translateY(-4px)'"
             onmouseout="this.style.borderColor='var(--border)';this.style.boxShadow='none';this.style.transform=''">
          <div style="font-size:56px;margin-bottom:16px;">${f.icon}</div>
          <div style="font-size:18px;font-weight:700;margin-bottom:8px;color:var(--text);">${f.name}</div>
          <div style="font-size:13px;color:var(--text-secondary);margin-bottom:16px;">${f.desc}</div>
          <div style="display:inline-block;background:${f.color};color:white;font-size:14px;font-weight:600;padding:6px 18px;border-radius:20px;">
            ${count} 个文件
          </div>
        </div>
      `;
    }).join('');
    
  } catch (e) {
    container.innerHTML = `<div style="color:var(--danger);grid-column:1/-1;">加载失败: ${e.message}</div>`;
  }
}

// 打开文件夹（显示该分类下的所有文件）
async function openKFolder(category) {
  const folder = KM_FOLDERS.find(f => f.id === category);
  if (!folder) return;
  
  _kmCurrentCategory = category;
  document.getElementById('km-folder-view').style.display = 'none';
  document.getElementById('km-file-view').style.display = '';
  document.getElementById('km-current-folder-title').textContent = `${folder.icon} ${folder.name}`;
  
  await loadKFilesByCategory(category);
}

// 按分类加载文件
async function loadKFilesByCategory(category) {
  const container = document.getElementById('km-file-list');
  container.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-secondary);grid-column:1/-1;">加载中...</div>';
  
  try {
    const resp = await fetch(`${KM_API}/list?category=${category}`, {
      headers: { 'Authorization': `Bearer ${authToken}` }
    });
    const data = await resp.json();
    _kmAllFiles = data.files || [];
    renderKFiles(_kmAllFiles);
  } catch (e) {
    container.innerHTML = `<div style="color:var(--danger);grid-column:1/-1;">加载失败: ${e.message}</div>`;
  }
}

// 搜索/过滤当前文件列表
function filterKFiles() {
  const keyword = (document.getElementById('km-search-input').value || '').toLowerCase();
  if (!_kmAllFiles.length) return;
  const filtered = keyword 
    ? _kmAllFiles.filter(f => (f.filename || '').toLowerCase().includes(keyword))
    : _kmAllFiles;
  renderKFiles(filtered);
}

// 重写 loadKFiles（供上传后刷新使用）
async function loadKFiles() {
  if (_kmCurrentCategory) {
    await loadKFilesByCategory(_kmCurrentCategory);
  } else {
    await loadKFolderView();
  }
}
'''

# 在 renderKFiles 函数前插入新JS
marker = '// 渲染知识库文件列表\nfunction renderKFiles(files) {'
if marker in content:
    content = content.replace(marker, js_functions + '\n' + marker)
    print("[OK] 文件夹视图JS函数已添加")
else:
    print("[WARN] 未找到 renderKFiles 标记，JS函数可能未添加")

# 3. 修改 switchPanel 中 knowledge_management 的初始化调用
# 将 loadKFiles() 改为 showKFolderView()
old_init = "if (panel === 'knowledge_management') { loadKFiles(); }"
new_init = "if (panel === 'knowledge_management') { showKFolderView(); }"
if old_init in content:
    content = content.replace(old_init, new_init)
    print("[OK] switchPanel 初始化已更新为 showKFolderView()")
else:
    print("[INFO] switchPanel 中未找到 knowledge_management 初始化代码（可能已更新）")

with open(HTML, 'w', encoding='utf-8') as f:
    f.write(content)

print("\n✅ 知识库文件夹视图修改完成！")
print("   刷新浏览器后生效（Ctrl+F5）")
