# scripts/test_gemini_analysis.py
import requests
import time
import json
import urllib3
import re

# Suppress InsecureRequestWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

AURA_URL = "https://aura.integrityinnovation.cloud"
TEST_DOMAIN = "pizzadelivery.ai"

def main():
    session = requests.Session()
    session.verify = False 

    # --- Step 1: Login ---
    login_url = f"{AURA_URL}/login"
    login_payload = {"username": "admin", "password": "firehorse"}
    
    print("Attempting to log in...")
    try:
        r = session.post(login_url, data=login_payload, allow_redirects=False)
        r.raise_for_status()
        if r.status_code not in [302, 307]:
             print(f"Login failed! Status: {r.status_code}. Expected a 302 or 307 redirect.")
             return
        print("Login successful.")
        
    except requests.exceptions.RequestException as e:
        print(f"Login request failed: {e}")
        return

    # --- Step 2: Ensure domain exists to get an ID ---
    domain_id = None
    try:
        print(f"Checking if domain '{TEST_DOMAIN}' exists...")
        get_domain_url = f"{AURA_URL}/api/domains/{TEST_DOMAIN}"
        r_get = session.get(get_domain_url)
        
        if r_get.status_code == 200:
            domain_id = r_get.json().get("id")
            print(f"Domain '{TEST_DOMAIN}' already exists with ID: {domain_id}")
        elif r_get.status_code == 404:
            # The UI creates domains via a form POST to the root dashboard page
            create_domain_url = f"{AURA_URL}/" 
            create_payload = {"domain_name": TEST_DOMAIN}
            print(f"Domain not found. Creating '{TEST_DOMAIN}' via form POST...")
            
            # This POST will redirect, so we follow it to get the dashboard page
            r_create = session.post(create_domain_url, data=create_payload, allow_redirects=True)
            r_create.raise_for_status()
            
            # Scrape the HTML of the dashboard to find the newly created domain ID
            # This is brittle, but it's the only way without a dedicated API endpoint
            match = re.search(r'data-domain-id="(\d+)"[^>]*>pizzadelivery\.ai<', r_create.text)
            if match:
                domain_id = int(match.group(1))
                print(f"Successfully created and found domain ID: {domain_id}")
            else:
                print("FAILURE: Could not find the new domain ID on the dashboard after creation.")
                return
        else:
            print(f"Unexpected status code when checking domain: {r_get.status_code}")
            r_get.raise_for_status()

    except requests.exceptions.RequestException as e:
        print(f"Failed to ensure domain exists: {e}")
        if e.response: print("Response:", e.response.text)
        return

    if not domain_id:
        print("Could not obtain domain_id. Aborting.")
        return

    # --- Step 3: Trigger the analysis job ---
    analyze_url = f"{AURA_URL}/api/job/analyze"
    analyze_payload = {"domain_id": domain_id, "niche_hints": "Italian food, local delivery, online ordering"}
    
    print(f"\nTriggering analysis for domain ID {domain_id}...")
    try:
        r = session.post(analyze_url, json=analyze_payload)
        r.raise_for_status()
        response_data = r.json()
        print("Analysis job triggered successfully.")
        print("Job Info:", response_data)
        
        job_id = response_data.get("job_id")
        if not job_id:
            print("Error: No job_id returned.")
            return

        # --- Step 4: Poll the job status ---
        job_status_url = f"{AURA_URL}/api/job/{job_id}"
        for i in range(24): # Poll for up to 120 seconds
            time.sleep(5)
            print(f"Polling job status... (Attempt {i+1}/24)")
            r_status = session.get(job_status_url)
            if r_status.status_code != 200:
                print(f"  Failed to get status: {r_status.status_code}")
                continue
            
            status_data = r_status.json()
            status = status_data.get('status', 'N/A')
            step = status_data.get('current_step_key', 'N/A')
            print(f"  Status: {status}, Step: {step}")

            if status == 'completed':
                print("\nSUCCESS: Gemini API call for domain analysis completed.")
                print("Final Status:", json.dumps(status_data, indent=2))
                return
            if status == 'failed':
                print("\nFAILURE: Job failed.")
                print("Final Status:", json.dumps(status_data, indent=2))
                return
        
        print("\nFAILURE: Job did not complete in the allotted time.")

    except requests.exceptions.RequestException as e:
        print(f"Analysis request failed: {e}")
        if e.response: print("Response Body:", e.response.text[:1000])
    except json.JSONDecodeError:
        print("Failed to decode JSON from response.")
        print("Response Text:", r.text[:1000])

if __name__ == "__main__":
    main()
