import torch
import torch.nn as nn
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from dno.core.organism import OrganismManager, BaseEvolvableModule
from dno.core.network import DynamicNetwork
from dno.config import DnoConfig
from dno.utils.dashboard import print_organism_status

def simple_linear_factory(type_name):
    # Helper to reconstruct generic Linear layers
    if type_name == 'Linear':
        return nn.Linear(10, 10)
    elif 'Sequential' in type_name:
         return nn.Linear(10, 10) # Mock
    return nn.Linear(10, 10) # Fallback

def test_phase5_interface():
    print("--- Starting Phase 5 Verification ---")
    
    # 1. Test Config
    print("\n[Test] DnoConfig")
    config = DnoConfig(entropy_threshold=0.9, vram_limit_gb=8.0)
    config.save("test_config.json")
    loaded = DnoConfig.load("test_config.json")
    if loaded.vram_limit_gb == 8.0:
        print("[PASS] Config save/load successful.")
    else:
        print("[FAIL] Config mismatch.")
        
    # 2. Test Dashboard & Reporting
    print("\n[Test] Dashboard & Evolution Report")
    manager = OrganismManager()
    network = DynamicNetwork(manager, config)
    
    # Create a small organism
    l1 = BaseEvolvableModule(nn.Linear(10, 10))
    l2 = BaseEvolvableModule(nn.Linear(10, 10))
    l1.dynamic_id = "layer_1"
    l2.dynamic_id = "layer_2"
    
    network.add_layer(l1) # Birth logged
    network.add_layer(l2, parents=[l1.dynamic_id]) # Birth logged
    
    # Simulate an event
    manager.log_event("DEATH", "Layer X removed")
    
    # Print Dashboard
    print("[VISUAL CHECK] Dashboard output below:")
    print_organism_status(manager)
    
    # Check Report
    report = manager.summarize_evolution()
    print("[VISUAL CHECK] Report output below:")
    print(report)
    
    if "Total Births" in report and "Total Deaths" in report:
        print("[PASS] Report generated.")
    else:
        print("[FAIL] Report malformed.")
        
    # 3. Test Fluid Serialization (.dno)
    print("\n[Test] Fluid Serialization (.dno)")
    
    # Save
    save_path = "test_organism"
    network.save_dno(save_path)
    
    # Load
    resurrected = DynamicNetwork.load_dno(save_path + ".dno", simple_linear_factory)
    
    # Verify
    if len(resurrected.manager.registry) == 2:
        print("[PASS] Topology restored.")
    else:
        print("[FAIL] Topology mismatch.")
        
    # Check if history loaded
    if len(resurrected.manager.genome_history) >= 2:
        print("[PASS] History restored.")
        
    # Clean up
    if os.path.exists("test_config.json"): os.remove("test_config.json")
    if os.path.exists("test_organism.dno"): os.remove("test_organism.dno")

    print("\n--- Phase 5 Verification Complete ---")

if __name__ == "__main__":
    test_phase5_interface()
