import requests
import json
from datetime import datetime
import time
import re

def get_csrf_token(html_content):
    """从HTML内容中提取CSRF token"""
    match = re.search(r'name="csrf_token" type="hidden" value="([^"]+)"', html_content)
    if match:
        return match.group(1)
    return None

def test_calculation(session, test_data, scenario_name):
    """执行单个测试场景"""
    print(f"\n测试场景: {scenario_name}")
    print("输入数据:")
    print(json.dumps(test_data, indent=2, ensure_ascii=False))
    
    try:
        # 发送计算请求
        calc_response = session.post('https://moldcost.jimmygan.com/calculate', data=test_data)
        
        # 打印响应状态和头信息
        print(f"\n响应状态码: {calc_response.status_code}")
        print("响应头:")
        print(json.dumps(dict(calc_response.headers), indent=2, ensure_ascii=False))
        
        # 打印响应内容
        print("\n响应内容:")
        print(calc_response.text)
        
        # 尝试解析JSON
        try:
            result = calc_response.json()
            print("\n解析后的JSON:")
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return result
        except json.JSONDecodeError as e:
            print(f"\nJSON解析错误: {str(e)}")
            return {'status': 'error', 'message': 'Invalid JSON response'}
            
    except requests.exceptions.RequestException as e:
        print(f"\n请求错误: {str(e)}")
        return {'status': 'error', 'message': str(e)}

def run_tests():
    # 基础URL
    base_url = 'https://moldcost.jimmygan.com'
    
    # 创建会话以保持cookie
    session = requests.Session()
    session.verify = False  # 忽略SSL验证
    
    try:
        # 1. 首先获取登录页面以获取CSRF token
        print("\n获取登录页面...")
        login_page = session.get(f'{base_url}/auth/login')
        print(f"登录页面状态码: {login_page.status_code}")
        
        # 从页面内容获取CSRF token
        csrf_token = get_csrf_token(login_page.text)
        print(f"CSRF Token: {csrf_token}")
        
        if not csrf_token:
            print("无法获取CSRF token")
            return
        
        # 2. 登录
        print("\n尝试登录...")
        login_data = {
            'email': 'admin@moldcost.com',
            'password': 'XViQLV6XE92HeYb1r3Xk3Q',
            'csrf_token': csrf_token,
            'remember_me': False
        }
        
        login_response = session.post(f'{base_url}/auth/login', data=login_data)
        print(f"登录响应状态码: {login_response.status_code}")
        print("登录响应头:")
        print(json.dumps(dict(login_response.headers), indent=2, ensure_ascii=False))
        
        # 检查登录是否成功
        if login_response.status_code != 200:
            print("登录失败")
            print("响应内容:")
            print(login_response.text)
            return
        
        # 等待一下确保登录完成
        time.sleep(1)
        
        # 获取计算页面以获取新的CSRF token
        calc_page = session.get(f'{base_url}/calculator')
        csrf_token = get_csrf_token(calc_page.text)
        
        if not csrf_token:
            print("无法获取计算页面的CSRF token")
            return
        
        # 基础数据
        base_data = {
            'mold_shop_name': 'ACMI',
            't1_factory_name': 'Test Factory 1',
            't2_component_factory': 'Test Factory 2',
            'model_name': 'Test Model',
            'tooling_id': '12345',
            'season': 'SS26',
            'stage': 'CR0',
            'country': 'China',
            'issue_date': datetime.now().strftime('%Y-%m-%d'),
            'csrf_token': csrf_token
        }
        
        # 测试场景1：基础场景
        test_data_1 = base_data.copy()
        test_data_1.update({
            'mold_main_type': 'Flat Rubber',
            'mold_sub_type': 'Flat & Thin',
            'complexity_high_sidewall': 'false',
            'sliders_count': '0',
            'cavity_count': '1',
            'digital_texture_type': 'adidas Digital Texture Library'
        })
        
        # 测试场景2：复杂场景
        test_data_2 = base_data.copy()
        test_data_2.update({
            'mold_main_type': 'Cupsole',
            'mold_sub_type': '3 Plates Mold',
            'complexity_high_sidewall': 'true',
            'sliders_count': '2',
            'cavity_count': '2',
            'digital_texture_type': 'Customized'
        })
        
        # 测试场景3：边界场景
        test_data_3 = base_data.copy()
        test_data_3.update({
            'mold_main_type': 'Rubber Sole',
            'mold_sub_type': 'Visible PL',
            'complexity_high_sidewall': 'true',
            'sliders_count': '4',
            'cavity_count': '4',
            'digital_texture_type': 'Lasering'
        })
        
        # 执行测试
        results = []
        results.append(test_calculation(session, test_data_1, "基础场景"))
        time.sleep(1)  # 添加延迟
        results.append(test_calculation(session, test_data_2, "复杂场景"))
        time.sleep(1)  # 添加延迟
        results.append(test_calculation(session, test_data_3, "边界场景"))
        
        # 分析结果
        print("\n测试结果分析:")
        for i, result in enumerate(results):
            print(f"\n场景 {i+1} 分析:")
            if result.get('status') == 'success':
                calc = result.get('calculation', {})
                print(f"基础价格: ${calc.get('net_base', 0)}")
                print(f"模具加成: ${calc.get('mold_factor', 0)}")
                print(f"复杂度加成: ${calc.get('complexity', 0)}")
                print(f"总价: ${calc.get('total', 0)}")
                
                # 验证计算
                expected_total = (calc.get('net_base', 0) + 
                                calc.get('mold_factor', 0) + 
                                calc.get('complexity', 0))
                if abs(expected_total - calc.get('total', 0)) < 0.01:
                    print("✓ 计算正确")
                else:
                    print("✗ 计算错误")
                    print(f"预期总价: ${expected_total}")
                    print(f"实际总价: ${calc.get('total', 0)}")
            else:
                print(f"测试失败: {result.get('message', 'Unknown error')}")
                
    except Exception as e:
        print(f"\n测试过程中发生错误: {str(e)}")

if __name__ == '__main__':
    run_tests() 