"""
自动化测试模板管理功能
使用Playwright自动化浏览器操作
"""

from playwright.sync_api import sync_playwright
import time
import os

BASE_URL = "http://localhost:8000"

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

        try:
            print("=" * 60)
            print("Starting Template Management Automated Test")
            print("=" * 60)

            # 步骤1: 访问超级管理员控制台
            print("\n[1/10] Visiting 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.png', full_page=True)
            print("    Screenshot saved: /tmp/admin_console.png")

            # 检查是否需要登录
            current_url = page.url
            if 'login' in current_url:
                print("    Login required! Please login manually...")
                print("    After login, please run this script again")
                input("Press Enter after login to continue...")
                page.goto(f"{BASE_URL}/static/super_admin.html")
                page.wait_for_load_state('networkidle')
                page.wait_for_timeout(2000)

            # 步骤2: 切换到模板管理标签页
            print("\n[2/10] Switching to Template Management tab...")
            template_tab = page.locator('[data-tab="templates-tab"]')
            template_tab.click()
            page.wait_for_timeout(1000)
            print("    Tab switched successfully")

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

            # 步骤4: 下载当前模板
            print("\n[4/10] 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}")

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

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

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

            # 步骤6: 上传测试模板
            print("\n[6/10] 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(3000)

            # 步骤7: 检查上传结果
            print("\n[7/10] 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 (checking if succeeded anyway)")

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

            # 步骤8: 再次下载验证内容
            print("\n[8/10] 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: {verification_filename}")

            # 步骤9: 恢复原始模板
            print("\n[9/10] 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(3000)

                # 检查恢复结果
                restore_msg = page.locator('.message.show')
                if restore_msg.count() > 0:
                    restore_text = restore_msg.text_content()
                    print(f"    Restore message: {restore_text}")
            else:
                print(f"    WARNING: Original template not found: {original_backup}")
                print("    Please upload the original template manually")

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

            print("\n" + "=" * 60)
            print("Test completed successfully!")
            print("=" * 60)
            print("\nSummary:")
            print(f"  - Downloaded original template: {original_filename}")
            print(f"  - Uploaded test template: {test_template}")
            print(f"  - Verified update")
            print(f"  - Downloaded for verification: {verification_filename}")
            print(f"  - Restored original template")

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

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

        finally:
            print("\nClosing browser...")
            browser.close()

if __name__ == "__main__":
    test_template_management()
