import subprocess
import json
import time
from datetime import datetime

OUTPUT_FILE = r"E:\genesis-system\staging\google_capability_map.json"

def run_cmd(cmd):
    try:
        # Utilize the verified gcloud path
        full_cmd = f'& "E:\\gcloud\\google-cloud-sdk\\bin\\gcloud.cmd" {cmd} --format=json'
        result = subprocess.run(["powershell", "-Command", full_cmd], capture_output=True, text=True)
        if result.returncode != 0:
            print(f"Error running {cmd}: {result.stderr}")
            return None
        return json.loads(result.stdout)
    except Exception as e:
        print(f"Exception cmd {cmd}: {e}")
        return None

def main():
    print("--- GENESIS GOOGLE ECOSYSTEM SURVEYOR ---")
    timestamp = datetime.now().isoformat()
    
    ecosystem = {
        "timestamp": timestamp,
        "services": [],
        "projects": [],
        "regions": []
    }

    # 1. Active Project
    print("Scanning Projects...")
    projects = run_cmd("projects list")
    if projects:
        ecosystem["projects"] = projects
        print(f"Found {len(projects)} projects.")

    # 2. Enabled Services
    print("Scanning Enabled Services...")
    services = run_cmd("services list --enabled")
    if services:
        cleaned_services = []
        for s in services:
            cleaned_services.append({
                "name": s.get("config", {}).get("name", "unknown"),
                "title": s.get("config", {}).get("title", "unknown"),
                "state": s.get("state", "unknown")
            })
        ecosystem["services"] = cleaned_services
        print(f"Found {len(cleaned_services)} enabled services.")

    # 3. Compute Regions (Availability)
    print("Scanning Compute Regions...")
    regions = run_cmd("compute regions list")
    if regions:
        ecosystem["regions"] = [r['name'] for r in regions]
        print(f"Found {len(regions)} regions.")
        
    # Save Map
    with open(OUTPUT_FILE, "w") as f:
        json.dump(ecosystem, f, indent=2)
    
    print(f"--- MAP SAVED: {OUTPUT_FILE} ---")

if __name__ == "__main__":
    main()
