"""
完整的模板管理测试 - 包含登录和上传功能
使用管理员账号: admin / adminpassword123
"""

from playwright.sync_api import sync_playwright
import time
import os
import requests

BASE_URL = "http://localhost:8000"

def test_complete_template_management():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        try:
            print("=" * 60)
            print("Complete Template Management Test with Login")
            print("=" * 60)

            # 步骤1: 访问登录页面
            print("\n[1/12] Accessing login page...")
            page.goto(f"{BASE_URL}/fs-ai-asistant/api/workflow/lawrisk/login")
            page.wait_for_load_state('networkidle')
            page.wait_for_timeout(2000)

            # 截图登录页面
            page.screenshot(path='/tmp/login_page.png', full_page=True)
            print("    Screenshot saved: /tmp/login_page.png")

            # 步骤2: 登录管理员账号
            print("\n[2/12] Logging in as admin...")
            page.fill('input[name="username"]', 'admin')
            page.fill('input[name="password"]', 'adminpassword123')

            # 点击登录按钮
            page.click('button[type="submit"]')
            page.wait_for_timeout(3000)

            # 检查登录成功
            current_url = page.url
            print(f"    After login, URL: {current_url}")

            if 'login' not in current_url.lower():
                print("    ✅ Login successful!")
            else:
                print("    ⚠️ Still on login page, checking for error...")
                error_msg = page.locator('.error, .alert, .message').text_content()
                if error_msg:
                    print(f"    Error message: {error_msg}")
                else:
                    print("    No visible error message")

            # 步骤3: 访问超级管理员控制台
            print("\n[3/12] Accessing super admin console...")
            page.goto(f"{BASE_URL}/static/super_admin.html")
            page.wait_for_load_state('networkidle')
            page.wait_for_timeout(2000)

            # 截图控制台
            page.screenshot(path='/tmp/admin_console_after_login.png', full_page=True)
            print("    Screenshot saved: /tmp/admin_console_after_login.png")

            # 验证是否成功访问
            if 'super_admin' in page.url or 'login' not in page.url:
                print("    ✅ Admin console accessible!")
            else:
                print("    ❌ Failed to access admin console")

            # 步骤4: 切换到模板管理标签页
            print("\n[4/12] Switching to Template Management tab...")
            template_tab = page.locator('[data-tab="templates-tab"]')

            # 等待标签页可点击
            template_tab.wait_for(state='visible', timeout=10000)
            template_tab.click()
            page.wait_for_timeout(1000)
            print("    ✅ Tab switched successfully")

            # 步骤5: 检查当前模板信息
            print("\n[5/12] Checking current template metadata...")
            template_meta = page.locator('#templateMeta').text_content()
            print(f"    Current template info:")
            print(f"    {template_meta}")

            # 步骤6: 下载当前模板
            print("\n[6/12] Downloading current template...")
            with page.expect_download() as download_info:
                download_btn = page.locator('#downloadTemplateBtn')
                download_btn.click()
                page.wait_for_timeout(2000)

            download = download_info.value
            original_filename = download.suggested_filename
            print(f"    ✅ Downloaded: {original_filename}")

            # 步骤7: 准备上传测试模板
            print("\n[7/12] Preparing test template upload...")
            test_template = "RiskTemplate_Test.xlsx"

            if not os.path.exists(test_template):
                print(f"    ❌ Test template not found: {test_template}")
                print("    Please run test_template_management_simple.py first to create it")
                return

            print(f"    ✅ Test template ready: {test_template}")

            # 步骤8: 上传测试模板
            print("\n[8/12] Uploading test template...")
            file_input = page.locator('input[type="file"][name="file"]')

            # 选择文件
            file_input.set_input_files(test_template)
            print(f"    ✅ File selected: {test_template}")

            # 提交表单
            form = page.locator('#templateForm')
            form_submit = form.locator('button[type="submit"]')
            form_submit.click()
            print("    ✅ Form submitted")

            # 等待处理
            page.wait_for_timeout(5000)

            # 步骤9: 检查上传结果
            print("\n[9/12] Checking upload result...")
            success_msg = page.locator('.message.show')
            msg_count = success_msg.count()

            if msg_count > 0:
                message_text = success_msg.text_content()
                print(f"    ✅ Success message: {message_text}")
            else:
                print("    ⚠️ No success message detected")

            # 重新检查模板信息
            updated_meta = page.locator('#templateMeta').text_content()
            print(f"    Updated template metadata:")
            print(f"    {updated_meta}")

            # 步骤10: 验证上传 - 再次下载
            print("\n[10/12] Downloading template again to verify...")
            with page.expect_download() as download_info2:
                download_btn2 = page.locator('#downloadTemplateBtn')
                download_btn2.click()
                page.wait_for_timeout(2000)

            download2 = download_info2.value
            verification_filename = download2.suggested_filename
            print(f"    ✅ Downloaded for verification: {verification_filename}")

            # 步骤11: 恢复原始模板
            print("\n[11/12] Restoring original template...")
            original_backup = "RiskTemplate_Original.xlsx"

            if os.path.exists(original_backup):
                file_input.set_input_files(original_backup)
                print(f"    ✅ File selected: {original_backup}")

                form_submit.click()
                print("    ✅ Form submitted")
                page.wait_for_timeout(5000)

                # 检查恢复结果
                restore_msg = page.locator('.message.show')
                if restore_msg.count() > 0:
                    restore_text = restore_msg.text_content()
                    print(f"    ✅ Restore message: {restore_text}")

                print(f"    ✅ Original template restored successfully")
            else:
                print(f"    ⚠️ WARNING: Original template not found: {original_backup}")

            # 步骤12: 最终验证
            print("\n[12/12] Final verification...")
            final_meta = page.locator('#templateMeta').text_content()
            print(f"    Final template metadata:")
            print(f"    {final_meta}")

            print("\n" + "=" * 60)
            print("🎉 Template Management Test Completed Successfully!")
            print("=" * 60)

            print("\n📊 Test Summary:")
            print(f"  ✅ Login successful with admin account")
            print(f"  ✅ Admin console accessible")
            print(f"  ✅ Template metadata viewing works")
            print(f"  ✅ Template download works")
            print(f"  ✅ Test template upload successful")
            print(f"  ✅ Upload verification successful")
            print(f"  ✅ Original template restoration successful")
            print(f"\n🎯 All core features working properly!")

        except Exception as e:
            print(f"\n❌ ERROR: {e}")
            import traceback
            traceback.print_exc()

            # 保存错误截图
            page.screenshot(path='/tmp/error_screenshot.png', full_page=True)
            print("\n📷 Error screenshot saved: /tmp/error_screenshot.png")

        finally:
            print("\n🔒 Closing browser...")
            browser.close()

if __name__ == "__main__":
    # 首先验证测试文件存在
    if not os.path.exists("RiskTemplate_Test.xlsx"):
        print("Creating test template first...")
        import subprocess
        subprocess.run(["python", "test_template_management_simple.py"])
        print("\n" + "="*60 + "\n")

    test_complete_template_management()
