#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup

password = "Zx189Y***"
email = "zishadeng@gmail.com"

session = requests.Session()
session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})

# Get login page first to get any tokens
print("获取登录页面...")
response = session.get('https://www.namesilo.com/login.php')
soup = BeautifulSoup(response.text, 'html.parser')

# Find CSRF token if exists
csrf_token = None
for input_tag in soup.find_all('input', {'type': 'hidden'}):
    if 'token' in input_tag.get('name', '').lower() or 'csrf' in input_tag.get('name', '').lower():
        csrf_token = input_tag.get('value')
        print(f"找到CSRF token: {csrf_token[:20]}...")
        break

# Login
login_data = {
    'email': email,
    'password': password,
}
if csrf_token:
    login_data['csrf_token'] = csrf_token

print(f"正在登录: {email}")
response = session.post('https://www.namesilo.com/login.php', data=login_data, allow_redirects=True)

# Check if logged in
if 'logout' in response.text.lower() or 'sign out' in response.text.lower():
    print("✓ 登录成功")
    
    # Get API Manager page
    print("访问API管理页面...")
    response = session.get('https://www.namesilo.com/account/api-manager')
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Find API keys in various possible formats
    api_keys = []
    
    # Look for code/pre tags
    for tag in soup.find_all(['code', 'pre', 'span', 'div']):
        text = tag.get_text(strip=True)
        if len(text) >= 20 and len(text) <= 100 and text.replace('-', '').replace('_', '').isalnum():
            api_keys.append(text)
    
    # Look in table cells
    for td in soup.find_all('td'):
        text = td.get_text(strip=True)
        if len(text) >= 20 and len(text) <= 100 and text.replace('-', '').replace('_', '').isalnum():
            api_keys.append(text)
    
    api_keys = list(set(api_keys))  # Remove duplicates
    
    if api_keys:
        print(f"\n找到 {len(api_keys)} 个API密钥:")
        for i, key in enumerate(api_keys, 1):
            print(f"  {i}. {key}")
        
        with open('namesilo_apikey.txt', 'w') as f:
            f.write(api_keys[0])
        print(f"\n✓ 已保存到 namesilo_apikey.txt")
    else:
        print("\n未找到API密钥")
        print("请手动访问: https://www.namesilo.com/account/api-manager")
        print("并将API密钥保存到 namesilo_apikey.txt")
else:
    print("✗ 登录失败")
    print("可能原因:")
    print("  1. 密码不正确")
    print("  2. 需要验证码或2FA")
    print("  3. 账户被锁定")
    print("\n请手动登录获取API密钥:")
    print("  1. 访问 https://www.namesilo.com/account/api-manager")
    print("  2. 复制API密钥")
    print("  3. 运行: echo 'YOUR_API_KEY' > namesilo_apikey.txt")
