"""
测试模板管理功能
1. 下载当前模板
2. 创建新的测试模板
3. 上传新模板并验证
4. 恢复原始模板
"""

import os
import sys
import requests
from pathlib import Path
import tempfile
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill

# Flask应用地址
BASE_URL = "http://localhost:8000"
API_BASE = f"{BASE_URL}/fs-ai-asistant/api/workflow/lawrisk"

def download_template():
    """下载当前模板"""
    print("Downloading current template...")

    try:
        response = requests.get(f"{API_BASE}/admin/permit-import/template")

        if response.status_code == 200:
            filename = "RiskTemplate_Original.xlsx"
            with open(filename, 'wb') as f:
                f.write(response.content)
            print(f"Original template downloaded: {filename} ({len(response.content)} bytes)")
            return filename
        else:
            print(f"Download failed: HTTP {response.status_code}")
            return None
    except Exception as e:
        print(f"Download error: {e}")
        return None

def create_test_template():
    """创建新的测试模板"""
    print("\nCreating test template...")

    wb = Workbook()
    ws = wb.active
    ws.title = "RiskTemplate"

    # 添加标题
    ws['A1'] = "Risk Prompt Template - Test Version"
    ws['A1'].font = Font(bold=True, size=14)
    ws['A1'].fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")

    # 添加表头
    headers = ['Region', 'Theme', 'Permit Name', 'Risk Content', 'Legal Basis', 'Document No']
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=3, column=col, value=header)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")

    # 添加测试数据
    test_data = [
        ['City-level', 'Catering', 'Food License', 'No license risk', 'Food Safety Law', 'DOC-2024-001'],
        ['Chancheng', 'Accommodation', 'Special Industry License', 'Unlicensed operation', 'Special Industry Law', 'DOC-2024-002'],
        ['Shunde', 'Entertainment', 'Entertainment License', 'No license risk', 'Entertainment Reg', 'DOC-2024-003'],
    ]

    for row, data in enumerate(test_data, 4):
        for col, value in enumerate(data, 1):
            ws.cell(row=row, column=col, value=value)

    # 保存文件
    filename = "RiskTemplate_Test.xlsx"
    wb.save(filename)
    print(f"Test template created: {filename}")
    return filename

def check_flask_status():
    """检查Flask应用状态"""
    try:
        response = requests.get(BASE_URL, timeout=5)
        print(f"Flask app is running: {BASE_URL}")
        return True
    except Exception as e:
        print(f"Cannot connect to Flask app: {e}")
        print("Please ensure Flask is running: python app.py")
        return False

def main():
    print("=" * 60)
    print("Template Management Test")
    print("=" * 60)

    # 检查Flask应用状态
    if not check_flask_status():
        return

    # 第一步：下载原始模板
    original_template = download_template()
    if not original_template:
        print("Cannot download original template, but continuing test...")

    # 第二步：创建测试模板
    test_template = create_test_template()

    print("\n" + "=" * 60)
    print("Manual Testing Steps")
    print("=" * 60)
    print("\nPlease follow these steps to test template management:")
    print("\n1. Open browser and visit admin console:")
    print(f"   {BASE_URL}/static/super_admin.html")
    print("\n2. Login if required")
    print("\n3. Click 'Template Management' tab")
    print("\n4. Check current template info")
    print("\n5. Click 'Download Current Template' button")
    print("\n6. Click 'Choose File' and select test template:")
    print(f"   {test_template}")
    print("\n7. Click 'Override Template' button to upload")
    print("\n8. Verify success message and updated metadata")
    print("\n9. Download template again to verify content")
    print("\n10. Upload original template to restore:")
    print(f"    {original_template if original_template else 'data/template/风险提示表 模板.xlsx'}")
    print("\n" + "=" * 60)

if __name__ == "__main__":
    main()
