import sys
import os
import time
import json
import requests
from bs4 import BeautifulSoup

# Ensure backend running
BASE_URL = "http://localhost:9988"

PAGES = {
    "Dashboard": "/",
    "Senate": "/senate",
    "Forge": "/forge",
    "Vault": "/vault",
    "Settings": "/settings"
}

def audit_with_bs4():
    print("Starting BS4 Audit...")
    results = {}
    
    with requests.Session() as s:
        for name, path in PAGES.items():
            url = f"{BASE_URL}{path}"
            try:
                r = s.get(url)
                if r.status_code != 200:
                    results[name] = {"status": "FAIL", "code": r.status_code}
                    continue
                
                soup = BeautifulSoup(r.text, 'html.parser')
                title = soup.title.string.strip() if soup.title else "No Title"
                h1 = soup.find('h1')
                h1_text = h1.text.strip() if h1 else "No H1"
                
                # Check for nav
                nav = soup.find('nav') or soup.find(class_='navbar') or soup.find(class_='sidebar')
                has_nav = bool(nav)
                
                results[name] = {
                    "status": "OK",
                    "title": title,
                    "h1": h1_text,
                    "has_nav": has_nav,
                    "content_len": len(r.text)
                }
            except Exception as e:
                results[name] = {"status": "ERROR", "error": str(e)}
                
    return results

def audit_with_selenium():
    print("Attempting Selenium Audit...")
    try:
        from selenium import webdriver
        from selenium.webdriver.chrome.options import Options
        
        options = Options()
        try:
            # Try running headless if possible, or just normal
            options.add_argument("--headless=new") 
            driver = webdriver.Chrome(options=options)
        except:
             # Fallback to Edge or Firefox if Chrome fails find
             try:
                 driver = webdriver.Edge()
             except:
                 print("Could not initialize generic WebDriver.")
                 return None

        results = {}
        os.makedirs("audit_screenshots", exist_ok=True)

        for name, path in PAGES.items():
            url = f"{BASE_URL}{path}"
            driver.get(url)
            time.sleep(1) # Wait for JS
            
            screenshot_path = os.path.abspath(f"audit_screenshots/{name}.png")
            driver.save_screenshot(screenshot_path)
            
            # Analyze elements via Selenium
            title = driver.title
            try:
                h1 = driver.find_element("tag name", "h1").text
            except:
                h1 = "No H1"
                
            results[name] = {
                "status": "OK", 
                "title": title, 
                "h1": h1,
                "screenshot": screenshot_path
            }
            
        driver.quit()
        return results

    except Exception as e:
        print(f"Selenium failed: {e}")
        return None

def main():
    # Try requests first to verify server is up
    try:
        requests.get(BASE_URL)
    except:
        print(f"Server not running at {BASE_URL}")
        sys.exit(1)

    # Try Selenium
    # results = audit_with_selenium()
    # Selenium often tricky without path setup. Let's default to BS4 for reliability in this env 
    # unless specifically requested. But user asked for screenshots.
    
    results = audit_with_selenium()
    
    if not results:
        print("Falling back to BS4...")
        results = audit_with_bs4()
        results["mode"] = "BS4 (Text Only)"
    else:
        results["mode"] = "Selenium (Screenshots Captured)"
        
    print(json.dumps(results, indent=2))

if __name__ == "__main__":
    main()
