#!/usr/bin/env python3
"""
Demo script to test the logging functionality in the pipeline editor.
This simulates adding nodes and shows the terminal logging output.
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Set up Qt environment
os.environ['QT_QPA_PLATFORM'] = 'offscreen'

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer

# Create Qt application
app = QApplication(sys.argv)

# Mock the pipeline editor to test logging without full UI
from core.pipeline import get_pipeline_summary
from core.nodes.model_node import ModelNode
from core.nodes.input_node import InputNode
from core.nodes.output_node import OutputNode
from core.nodes.preprocess_node import PreprocessNode
from core.nodes.postprocess_node import PostprocessNode


class MockPipelineEditor:
    """Mock pipeline editor to test logging functionality."""
    
    def __init__(self):
        self.nodes = []
        self.previous_stage_count = 0
        print("🚀 Pipeline Editor initialized")
        self.analyze_pipeline()
    
    def add_node(self, node_type):
        """Add a node and trigger analysis."""
        if node_type == 'input':
            node = InputNode()
            print("🔄 Adding Input Node via toolbar...")
        elif node_type == 'model':
            node = ModelNode()
            print("🔄 Adding Model Node via toolbar...")
        elif node_type == 'output':
            node = OutputNode()
            print("🔄 Adding Output Node via toolbar...")
        elif node_type == 'preprocess':
            node = PreprocessNode()
            print("🔄 Adding Preprocess Node via toolbar...")
        elif node_type == 'postprocess':
            node = PostprocessNode()
            print("🔄 Adding Postprocess Node via toolbar...")
        
        self.nodes.append(node)
        print(f"➕ Node added: {node.NODE_NAME}")
        self.analyze_pipeline()
    
    def remove_last_node(self):
        """Remove the last node and trigger analysis."""
        if self.nodes:
            node = self.nodes.pop()
            print(f"➖ Node removed: {node.NODE_NAME}")
            self.analyze_pipeline()
    
    def clear_pipeline(self):
        """Clear all nodes."""
        print("🗑️ Clearing entire pipeline...")
        self.nodes.clear()
        self.analyze_pipeline()
    
    def analyze_pipeline(self):
        """Analyze the pipeline and show logging."""
        # Create a mock node graph
        class MockGraph:
            def __init__(self, nodes):
                self._nodes = nodes
            def all_nodes(self):
                return self._nodes
        
        graph = MockGraph(self.nodes)
        
        try:
            # Get pipeline summary
            summary = get_pipeline_summary(graph)
            current_stage_count = summary['stage_count']
            
            # Print detailed pipeline analysis
            self.print_pipeline_analysis(summary, current_stage_count)
            
            # Update previous count for next comparison
            self.previous_stage_count = current_stage_count
            
        except Exception as e:
            print(f"❌ Pipeline analysis error: {str(e)}")
    
    def print_pipeline_analysis(self, summary, current_stage_count):
        """Print detailed pipeline analysis to terminal."""
        # Check if stage count changed
        if current_stage_count != self.previous_stage_count:
            if self.previous_stage_count == 0:
                print(f"🎯 Initial stage count: {current_stage_count}")
            else:
                change = current_stage_count - self.previous_stage_count
                if change > 0:
                    print(f"📈 Stage count increased: {self.previous_stage_count} → {current_stage_count} (+{change})")
                else:
                    print(f"📉 Stage count decreased: {self.previous_stage_count} → {current_stage_count} ({change})")
        
        # Print current pipeline status
        print(f"📊 Current Pipeline Status:")
        print(f"   • Stages: {current_stage_count}")
        print(f"   • Total Nodes: {summary['total_nodes']}")
        print(f"   • Model Nodes: {summary['model_nodes']}")
        print(f"   • Input Nodes: {summary['input_nodes']}")
        print(f"   • Output Nodes: {summary['output_nodes']}")
        print(f"   • Preprocess Nodes: {summary['preprocess_nodes']}")
        print(f"   • Postprocess Nodes: {summary['postprocess_nodes']}")
        print(f"   • Valid: {'✅' if summary['valid'] else '❌'}")
        
        if not summary['valid'] and summary.get('error'):
            print(f"   • Error: {summary['error']}")
        
        # Print stage details if available
        if summary.get('stages'):
            print(f"📋 Stage Details:")
            for i, stage in enumerate(summary['stages'], 1):
                model_name = stage['model_config'].get('node_name', 'Unknown Model')
                preprocess_count = len(stage['preprocess_configs'])
                postprocess_count = len(stage['postprocess_configs'])
                
                stage_info = f"   Stage {i}: {model_name}"
                if preprocess_count > 0:
                    stage_info += f" (with {preprocess_count} preprocess)"
                if postprocess_count > 0:
                    stage_info += f" (with {postprocess_count} postprocess)"
                
                print(stage_info)
        
        print("─" * 50)  # Separator line


def demo_logging():
    """Demonstrate the logging functionality."""
    print("=" * 60)
    print("🔊 PIPELINE LOGGING DEMO")
    print("=" * 60)
    
    # Create mock editor
    editor = MockPipelineEditor()
    
    # Demo sequence: Build a pipeline step by step
    print("\n1. Adding Input Node:")
    editor.add_node('input')
    
    print("\n2. Adding Model Node (creates first stage):")
    editor.add_node('model')
    
    print("\n3. Adding Output Node:")
    editor.add_node('output')
    
    print("\n4. Adding Preprocess Node:")
    editor.add_node('preprocess')
    
    print("\n5. Adding second Model Node (creates second stage):")
    editor.add_node('model')
    
    print("\n6. Adding Postprocess Node:")
    editor.add_node('postprocess')
    
    print("\n7. Adding third Model Node (creates third stage):")
    editor.add_node('model')
    
    print("\n8. Removing a Model Node (decreases stages):")
    editor.remove_last_node()
    
    print("\n9. Clearing entire pipeline:")
    editor.clear_pipeline()
    
    print("\n" + "=" * 60)
    print("🎉 DEMO COMPLETED")
    print("=" * 60)
    print("\nAs you can see, the terminal logs show:")
    print("• When nodes are added/removed")
    print("• Stage count changes (increases/decreases)")
    print("• Current pipeline status with detailed breakdown")
    print("• Validation status and errors")
    print("• Individual stage details")


def main():
    """Run the logging demo."""
    try:
        demo_logging()
    except Exception as e:
        print(f"❌ Demo failed: {e}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    main()