import requests
from bs4 import BeautifulSoup

base_url = "http://173.212.199.208:8090"
session = requests.Session()

# 1. Get the login page to fetch CSRF token and cookie
print("1. Fetching login page...")
response = session.get(f"{base_url}/auth/login")
print(f"   Status: {response.status_code}")
print(f"   Cookies: {session.cookies.get_dict()}")

if response.status_code == 200:
    # Parse the CSRF token from the form
    soup = BeautifulSoup(response.text, 'html.parser')
    csrf_token = None
    csrf_input = soup.find('input', {'name': 'csrfmiddlewaretoken'})
    if csrf_input:
        csrf_token = csrf_input.get('value')
        print(f"   CSRF Token from form: {csrf_token[:20]}...")
    
    # Also get CSRF token from cookie if available
    csrf_cookie = session.cookies.get('csrftoken')
    print(f"   CSRF Cookie: {csrf_cookie[:20] if csrf_cookie else 'Not found'}...")
    
    # 2. Try to login with the admin credentials
    print("\n2. Attempting login...")
    login_data = {
        'csrfmiddlewaretoken': csrf_token or csrf_cookie,
        'email': 'admin@adtlas.com',
        'password': 'Admin@123456',
    }
    
    headers = {
        'Referer': f'{base_url}/auth/login',
        'X-CSRFToken': csrf_token or csrf_cookie,
    }
    
    response = session.post(f"{base_url}/auth/login", data=login_data, headers=headers, allow_redirects=False)
    print(f"   Status: {response.status_code}")
    print(f"   Response headers: {dict(response.headers)}")
    
    if response.status_code == 302:
        print(f"   Redirect to: {response.headers.get('Location')}")
        print("   ✓ Login successful!")
    elif response.status_code == 403:
        print("   ✗ CSRF validation failed")
        print(f"   Response: {response.text[:500]}...")
    elif response.status_code == 200:
        # Check if there's an error message
        soup = BeautifulSoup(response.text, 'html.parser')
        error = soup.find('div', {'class': 'alert-danger'})
        if error:
            print(f"   ✗ Login error: {error.text.strip()}")
        else:
            print("   ✗ Login failed but no specific error found")
