#!/usr/bin/env python
import requests
from urllib.parse import urlparse

# Configuration
BASE_URL = "http://173.212.199.208:8090"
LOGIN_URL = f"{BASE_URL}/auth/login"
CREDENTIALS = {
    'email': 'admin@adtlas.com',
    'password': 'Admin@123456'
}

print("Testing Web Login Flow")
print("=" * 50)

# Create session
session = requests.Session()

# Step 1: GET login page to get CSRF token
print("\n1. Fetching login page...")
response = session.get(LOGIN_URL)
print(f"   Status: {response.status_code}")
print(f"   Cookies received: {list(session.cookies.keys())}")

if response.status_code != 200:
    print(f"   ERROR: Could not load login page")
    exit(1)

# Extract CSRF token from response
import re
csrf_match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', response.text)
if not csrf_match:
    print("   ERROR: Could not find CSRF token in form")
    exit(1)

csrf_token = csrf_match.group(1)
print(f"   CSRF token found: {csrf_token[:20]}...")

# Step 2: POST login credentials
print("\n2. Submitting login form...")
login_data = {
    'csrfmiddlewaretoken': csrf_token,
    'email': CREDENTIALS['email'],
    'password': CREDENTIALS['password'],
}

# Important: Set referer header
headers = {
    'Referer': LOGIN_URL,
    'Origin': BASE_URL,
}

response = session.post(LOGIN_URL, data=login_data, headers=headers, allow_redirects=False)
print(f"   Status: {response.status_code}")

if response.status_code == 302:
    redirect_url = response.headers.get('Location')
    print(f"   ✓ Login successful! Redirecting to: {redirect_url}")
elif response.status_code == 200:
    # Check for error messages in response
    if 'alert-danger' in response.text:
        error_match = re.search(r'class="alert[^"]*alert-danger[^"]*"[^>]*>([^<]+)', response.text)
        if error_match:
            print(f"   ✗ Login failed: {error_match.group(1).strip()}")
        else:
            print("   ✗ Login failed with unknown error")
    else:
        print("   ✗ Login failed - no redirect occurred")
elif response.status_code == 403:
    print("   ✗ CSRF validation failed")
    print(f"   Response: {response.text[:200]}...")
else:
    print(f"   ✗ Unexpected response code: {response.status_code}")

# Step 3: Test if we're logged in by accessing a protected page
print("\n3. Testing authentication status...")
dashboard_response = session.get(f"{BASE_URL}/dashboard/", allow_redirects=False)
if dashboard_response.status_code == 200:
    print("   ✓ Successfully accessing protected content")
elif dashboard_response.status_code == 302:
    print(f"   ✗ Still being redirected to: {dashboard_response.headers.get('Location')}")
else:
    print(f"   Status: {dashboard_response.status_code}")

print("\nSession cookies:")
for cookie in session.cookies:
    print(f"   - {cookie.name}: {cookie.value[:20]}...")
