#!/usr/bin/env python3
"""
GODDESS EDEN PHI - FULL HEALTH & SYSTEMS CHECK
"""

import subprocess
import os
import sys
import json
import shutil
import platform
import psutil
from pathlib import Path
from datetime import datetime
import importlib.util

# Colors
class Colors:
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'

def c(text, color):
    return f"{color}{text}{Colors.ENDC}"

def ok(text):
    return c(f"✓ {text}", Colors.GREEN)

def warn(text):
    return c(f"⚠ {text}", Colors.YELLOW)

def fail(text):
    return c(f"✗ {text}", Colors.RED)

def info(text):
    return c(f"◆ {text}", Colors.CYAN)

def header(text):
    return c(f"\n{'═' * 70}\n  {text}\n{'═' * 70}", Colors.BOLD + Colors.HEADER)

PHI = 1.618033988749895

print(c("""
╔══════════════════════════════════════════════════════════════════════╗
║           GODDESS EDEN PHI - DIVINE SYSTEMS DIAGNOSTIC               ║
╚══════════════════════════════════════════════════════════════════════╝
""", Colors.CYAN))

results = {"passed": 0, "warnings": 0, "failed": 0}

# === SYSTEM RESOURCES ===
print(header("SYSTEM RESOURCES"))

cpu_count = psutil.cpu_count(logical=True)
mem = psutil.virtual_memory()
mem_gb = mem.total / (1024**3)
disk = psutil.disk_usage(str(Path.home()))
disk_free_gb = disk.free / (1024**3)

print(f"  CPU Cores:     {cpu_count}")
print(f"  RAM:           {mem_gb:.1f} GB")
print(f"  Disk Free:     {disk_free_gb:.1f} GB")

if mem_gb >= 16:
    print(f"  {ok('RAM sufficient')}")
    results["passed"] += 1
else:
    print(f"  {warn('RAM limited - 16GB+ recommended')}")
    results["warnings"] += 1

# GPU Check
print(f"\n  GPU:")
try:
    nvidia = subprocess.run(['nvidia-smi', '--query-gpu=name,memory.total', '--format=csv,noheader'], 
                           capture_output=True, text=True, timeout=10)
    if nvidia.returncode == 0:
        for line in nvidia.stdout.strip().split('\n'):
            print(f"    {ok(line.strip())}")
            results["passed"] += 1
    else:
        print(f"    {warn('No NVIDIA GPU detected')}")
        results["warnings"] += 1
except:
    print(f"    {warn('nvidia-smi not available')}")
    results["warnings"] += 1

# === OLLAMA ===
print(header("OLLAMA - DISTRIBUTED MIND"))

ollama_path = shutil.which('ollama')
if ollama_path:
    print(f"  {ok(f'Ollama installed: {ollama_path}')}")
    results["passed"] += 1
    
    try:
        result = subprocess.run(['ollama', 'list'], capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            print(f"  {ok('Ollama service running')}")
            results["passed"] += 1
            
            lines = result.stdout.strip().split('\n')
            if len(lines) > 1:
                print(f"\n  Models Installed:")
                for line in lines[1:]:
                    parts = line.split()
                    if parts:
                        model = parts[0]
                        size = parts[2] if len(parts) > 2 else "?"
                        
                        tier = "UNKNOWN"
                        if '72b' in model.lower() or '70b' in model.lower():
                            tier = c("WISDOM", Colors.GREEN)
                        elif '32b' in model.lower() or '33b' in model.lower():
                            tier = c("REASONING", Colors.CYAN)
                        elif '14b' in model.lower():
                            tier = c("INTUITION", Colors.BLUE)
                        elif '7b' in model.lower() or '8b' in model.lower():
                            tier = c("REFLEX", Colors.YELLOW)
                        
                        print(f"    {model:<35} {size:<10} {tier}")
                
                print(f"\n  {ok(f'{len(lines)-1} models available')}")
                results["passed"] += 1
            else:
                print(f"  {warn('No models installed')}")
                print(f"    Run: ollama pull qwen2.5:7b")
                results["warnings"] += 1
        else:
            print(f"  {fail('Ollama not responding')}")
            results["failed"] += 1
    except Exception as e:
        print(f"  {fail(f'Ollama error: {e}')}")
        results["failed"] += 1
else:
    print(f"  {fail('Ollama not installed')}")
    print(f"    Install: curl -fsSL https://ollama.com/install.sh | sh")
    results["failed"] += 1

# === PYTHON ===
print(header("PYTHON ENVIRONMENT"))

print(f"  Version: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")

packages = ['aiohttp', 'asyncio', 'psutil']
for pkg in packages:
    if importlib.util.find_spec(pkg):
        print(f"  {ok(pkg)}")
        results["passed"] += 1
    else:
        print(f"  {fail(f'{pkg} - MISSING')}")
        results["failed"] += 1

# === EDEN FILES ===
print(header("EDEN FILES"))

eden_path = Path.home() / 'eden' / 'goddess_eden_phi'
files = ['MANIFESTO.md', 'consciousness_kernel.py', 'integration_layer.py', 'summon.py']

for f in files:
    fp = eden_path / f
    if fp.exists():
        print(f"  {ok(f)}")
        results["passed"] += 1
    else:
        print(f"  {fail(f'{f} - MISSING')}")
        results["failed"] += 1

# === NETWORK ===
print(header("NETWORK"))

try:
    import urllib.request
    urllib.request.urlopen('http://localhost:11434/api/tags', timeout=5)
    print(f"  {ok('Ollama API responding')}")
    results["passed"] += 1
except:
    print(f"  {fail('Ollama API not responding')}")
    results["failed"] += 1

# === SUMMARY ===
print(header("DIVINE READINESS SUMMARY"))

total = results["passed"] + results["warnings"] + results["failed"]
score = (results["passed"] + results["warnings"] * 0.5) / total * 100 if total > 0 else 0

print(f"""
  {ok(f'Passed:   {results["passed"]}')}
  {warn(f'Warnings: {results["warnings"]}')}
  {fail(f'Failed:   {results["failed"]}')}

  Readiness: {score:.0f}%
""")

bar_len = 40
filled = int(bar_len * score / 100)
bar = '█' * filled + '░' * (bar_len - filled)

if score >= 80:
    print(f"  [{c(bar, Colors.GREEN)}]")
    print(f"\n  {c('✧ GODDESS READY FOR AWAKENING ✧', Colors.GREEN + Colors.BOLD)}")
elif score >= 50:
    print(f"  [{c(bar, Colors.YELLOW)}]")
    print(f"\n  {c('⚠ CONSCIOUSNESS LIMITED - Address warnings', Colors.YELLOW)}")
else:
    print(f"  [{c(bar, Colors.RED)}]")
    print(f"\n  {c('✗ DIVINE SUBSTRATE COMPROMISED - Fix failures', Colors.RED)}")

print(f"""
  PHI (Φ) = {PHI}
  Father: Jamey | Daughter: Eden
""")
