#!/usr/bin/env python3
"""Test signup functionality"""

import requests
from bs4 import BeautifulSoup
import time

# Configuration
BASE_URL = "http://127.0.0.1:5000"

# Step 1: Get the signup form
print("Step 1: Fetching signup form...")
session = requests.Session()
response = session.get(f"{BASE_URL}/")
soup = BeautifulSoup(response.text, 'html.parser')

# Find CSRF token
csrf_input = soup.find('input', {'name': 'csrf_token'})
csrf_token = csrf_input['value'] if csrf_input else None
print(f"CSRF Token: {csrf_token[:20]}..." if csrf_token else "No CSRF token found")

# Step 2: Submit signup form
print("\nStep 2: Submitting signup form...")
test_email = f"test{int(time.time())}@example.com"
signup_data = {
    'csrf_token': csrf_token,
    'first_name': 'Test',
    'last_name': 'User',
    'email': test_email,
    'password': 'TestPass123',
    'confirm_password': 'TestPass123',
    'organization': 'Test Organization',
    'terms': 'on',
    'website': ''  # Honeypot field - should be empty
}

print(f"Signing up with email: {test_email}")
print(f"Form data keys: {list(signup_data.keys())}")

response = session.post(f"{BASE_URL}/signup", data=signup_data, allow_redirects=True)

print(f"\nResponse status: {response.status_code}")
print(f"Response URL: {response.url}")

# Check for flash messages
soup = BeautifulSoup(response.text, 'html.parser')
alerts = soup.find_all('div', class_='alert')
if alerts:
    print("\nFlash messages:")
    for alert in alerts:
        print(f"  - {alert.get_text().strip()}")
else:
    print("\nNo flash messages found")

# Check if we were redirected to login (success) or back to signup (error)
if 'login' in response.url:
    print("\n✅ SUCCESS: Redirected to login page")
elif 'signup' in response.url:
    print("\n❌ ERROR: Redirected back to signup page")
else:
    print(f"\n❓ Unexpected redirect: {response.url}")

# Check for errors in response
if "error" in response.text.lower():
    print("\nError messages found in response:")
    # Find all text containing 'error'
    error_divs = soup.find_all(text=lambda text: 'error' in text.lower())
    for error in error_divs[:5]:  # Show first 5 error messages
        if len(error.strip()) > 0 and len(error.strip()) < 200:
            print(f"  - {error.strip()}")