package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"chorus.services/bzzz/pkg/config"
	"chorus.services/bzzz/pkg/coordination"
	"chorus.services/bzzz/pkg/integration"
	"chorus.services/bzzz/pubsub"
	"github.com/libp2p/go-libp2p"
	"github.com/libp2p/go-libp2p/core/host"
)

// This example demonstrates how to integrate SLURP event system with BZZZ HMMM discussions
func main() {
	fmt.Println("🚀 SLURP Integration Example")
	
	// Create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	
	// Example 1: Basic SLURP Configuration
	basicSlurpIntegrationExample(ctx)
	
	// Example 2: Advanced Configuration with Project Mappings
	advancedSlurpConfigurationExample()
	
	// Example 3: Manual HMMM Discussion Processing
	manualDiscussionProcesssingExample(ctx)
	
	// Example 4: Real-time Integration Setup
	realtimeIntegrationExample(ctx)
	
	fmt.Println("✅ All examples completed successfully")
}

// Example 1: Basic SLURP integration setup
func basicSlurpIntegrationExample(ctx context.Context) {
	fmt.Println("\n📋 Example 1: Basic SLURP Integration Setup")
	
	// Create basic SLURP configuration
	slurpConfig := config.SlurpConfig{
		Enabled:     true,
		BaseURL:     "http://localhost:8080",
		APIKey:      "your-api-key-here",
		Timeout:     30 * time.Second,
		RetryCount:  3,
		RetryDelay:  5 * time.Second,
		
		EventGeneration: config.EventGenerationConfig{
			MinConsensusStrength:  0.7,
			MinParticipants:       2,
			RequireUnanimity:      false,
			MaxDiscussionDuration: 30 * time.Minute,
			MinDiscussionDuration: 1 * time.Minute,
			EnabledEventTypes: []string{
				"announcement", "warning", "blocker", "approval", 
				"priority_change", "access_update", "structural_change",
			},
		},
		
		DefaultEventSettings: config.DefaultEventConfig{
			DefaultSeverity:  5,
			DefaultCreatedBy: "hmmm-consensus",
			DefaultTags:      []string{"hmmm-generated", "automated"},
		},
	}
	
	fmt.Printf("✅ SLURP config created with %d enabled event types\n", 
		len(slurpConfig.EventGeneration.EnabledEventTypes))
	
	// Note: In a real application, you would create the integrator here:
	// integrator, err := integration.NewSlurpEventIntegrator(ctx, slurpConfig, pubsubInstance)
	fmt.Println("📝 Note: Create integrator with actual PubSub instance in real usage")
}

// Example 2: Advanced configuration with project-specific mappings
func advancedSlurpConfigurationExample() {
	fmt.Println("\n📋 Example 2: Advanced SLURP Configuration")
	
	// Create advanced configuration with project mappings
	slurpConfig := config.GetDefaultSlurpConfig()
	slurpConfig.Enabled = true
	slurpConfig.BaseURL = "https://slurp.example.com"
	
	// Add project-specific mappings
	slurpConfig.ProjectMappings = map[string]config.ProjectEventMapping{
		"/projects/frontend": {
			ProjectPath: "/projects/frontend",
			CustomEventTypes: map[string]string{
				"ui_change":      "structural_change",
				"performance":    "warning",
				"accessibility":  "priority_change",
			},
			SeverityOverrides: map[string]int{
				"blocker": 9, // Higher severity for frontend blockers
				"warning": 6, // Higher severity for frontend warnings
			},
			AdditionalMetadata: map[string]interface{}{
				"team":        "frontend",
				"impact_area": "user_experience",
			},
			EventFilters: []config.EventFilter{
				{
					Name: "critical_ui_filter",
					Conditions: map[string]string{
						"content_contains": "critical",
						"event_type":      "structural_change",
					},
					Action: "modify",
					Modifications: map[string]string{
						"severity": "10",
						"tag":      "critical-ui",
					},
				},
			},
		},
		"/projects/backend": {
			ProjectPath: "/projects/backend",
			CustomEventTypes: map[string]string{
				"api_change":     "structural_change",
				"security":       "blocker",
				"performance":    "warning",
			},
			SeverityOverrides: map[string]int{
				"security": 10, // Maximum severity for security issues
			},
			AdditionalMetadata: map[string]interface{}{
				"team":        "backend",
				"impact_area": "system_stability",
			},
		},
	}
	
	// Configure severity rules
	slurpConfig.EventGeneration.SeverityRules.UrgencyKeywords = append(
		slurpConfig.EventGeneration.SeverityRules.UrgencyKeywords,
		"security", "vulnerability", "exploit", "breach",
	)
	slurpConfig.EventGeneration.SeverityRules.UrgencyBoost = 3
	
	fmt.Printf("✅ Advanced config created with %d project mappings\n", 
		len(slurpConfig.ProjectMappings))
	fmt.Printf("✅ Urgency keywords: %v\n", 
		slurpConfig.EventGeneration.SeverityRules.UrgencyKeywords)
}

// Example 3: Manual HMMM discussion processing
func manualDiscussionProcesssingExample(ctx context.Context) {
	fmt.Println("\n📋 Example 3: Manual HMMM Discussion Processing")
	
	// Create a sample HMMM discussion context
	discussion := integration.HmmmDiscussionContext{
		DiscussionID:      "discussion-123",
		SessionID:         "session-456",
		Participants:      []string{"agent-frontend-01", "agent-backend-02", "agent-qa-03"},
		StartTime:         time.Now().Add(-10 * time.Minute),
		EndTime:           time.Now(),
		ConsensusReached:  true,
		ConsensusStrength: 0.85,
		OutcomeType:       "Frontend team approves migration to React 18",
		ProjectPath:       "/projects/frontend",
		Messages: []integration.HmmmMessage{
			{
				From:      "agent-frontend-01",
				Content:   "I propose we migrate to React 18 for better performance",
				Type:      "proposal",
				Timestamp: time.Now().Add(-8 * time.Minute),
			},
			{
				From:      "agent-backend-02",
				Content:   "That sounds good, it should improve our bundle size",
				Type:      "agreement",
				Timestamp: time.Now().Add(-6 * time.Minute),
			},
			{
				From:      "agent-qa-03",
				Content:   "Approved from QA perspective, tests are compatible",
				Type:      "approval",
				Timestamp: time.Now().Add(-3 * time.Minute),
			},
		},
		RelatedTasks: []string{"TASK-123", "TASK-456"},
		Metadata: map[string]interface{}{
			"migration_type": "framework_upgrade",
			"risk_level":     "low",
			"impact":         "high",
		},
	}
	
	fmt.Printf("✅ Sample discussion created:\n")
	fmt.Printf("   - ID: %s\n", discussion.DiscussionID)
	fmt.Printf("   - Participants: %d\n", len(discussion.Participants))
	fmt.Printf("   - Messages: %d\n", len(discussion.Messages))
	fmt.Printf("   - Consensus: %.1f%%\n", discussion.ConsensusStrength*100)
	fmt.Printf("   - Outcome: %s\n", discussion.OutcomeType)
	
	// Note: In real usage, you would process this with:
	// err := integrator.ProcessHmmmDiscussion(ctx, discussion)
	fmt.Println("📝 Note: Process with actual SlurpEventIntegrator in real usage")
}

// Example 4: Real-time integration setup with meta coordinator
func realtimeIntegrationExample(ctx context.Context) {
	fmt.Println("\n📋 Example 4: Real-time Integration Setup")
	
	// This example shows how to set up the complete integration
	// In a real application, you would use actual network setup
	
	fmt.Println("🔧 Setting up libp2p host...")
	// Create a basic libp2p host (simplified for example)
	host, err := libp2p.New(
		libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"),
	)
	if err != nil {
		log.Printf("❌ Failed to create host: %v", err)
		return
	}
	defer host.Close()
	
	fmt.Printf("✅ Host created with ID: %s\n", host.ID().ShortString())
	
	// Create PubSub system
	fmt.Println("🔧 Setting up PubSub system...")
	ps, err := pubsub.NewPubSub(ctx, host, "bzzz/coordination/v1", "hmmm/meta-discussion/v1")
	if err != nil {
		log.Printf("❌ Failed to create pubsub: %v", err)
		return
	}
	defer ps.Close()
	
	fmt.Println("✅ PubSub system initialized")
	
	// Create SLURP configuration
	slurpConfig := config.GetDefaultSlurpConfig()
	slurpConfig.Enabled = true
	slurpConfig.BaseURL = "http://localhost:8080"
	
	// Note: In real usage, you would create the integrator:
	// integrator, err := integration.NewSlurpEventIntegrator(ctx, slurpConfig, ps)
	// if err != nil {
	//     log.Printf("❌ Failed to create SLURP integrator: %v", err)
	//     return
	// }
	// defer integrator.Close()
	
	// Create meta coordinator
	fmt.Println("🔧 Setting up Meta Coordinator...")
	metaCoordinator := coordination.NewMetaCoordinator(ctx, ps)
	
	// Note: In real usage, you would attach the integrator:
	// metaCoordinator.SetSlurpIntegrator(integrator)
	
	fmt.Println("✅ Meta Coordinator initialized with SLURP integration")
	
	// Demonstrate event publishing
	fmt.Println("🔧 Publishing sample SLURP integration events...")
	
	// Publish a sample SLURP event generation notification
	err = ps.PublishSlurpEventGenerated(map[string]interface{}{
		"discussion_id": "sample-discussion-123",
		"event_type":    "approval",
		"participants":  []string{"agent-01", "agent-02"},
		"consensus":     0.9,
		"timestamp":     time.Now(),
	})
	if err != nil {
		log.Printf("❌ Failed to publish SLURP event: %v", err)
		return
	}
	
	// Publish a SLURP context update
	err = ps.PublishSlurpContextUpdate(map[string]interface{}{
		"context_type":   "project_update",
		"project_path":   "/projects/example",
		"update_type":    "event_generated",
		"timestamp":      time.Now(),
	})
	if err != nil {
		log.Printf("❌ Failed to publish context update: %v", err)
		return
	}
	
	fmt.Println("✅ Sample events published successfully")
	
	// Let the system run for a short time to process messages
	fmt.Println("⏳ Running system for 5 seconds...")
	time.Sleep(5 * time.Second)
	
	fmt.Println("✅ Real-time integration example completed")
}

// Utility function to demonstrate SLURP event mapping
func demonstrateEventMapping() {
	fmt.Println("\n📋 Event Mapping Demonstration")
	
	mapping := config.GetHmmmToSlurpMapping()
	
	fmt.Println("🗺️ HMMM to SLURP Event Type Mappings:")
	fmt.Printf("   - Consensus Approval → %s\n", mapping.ConsensusApproval)
	fmt.Printf("   - Risk Identified → %s\n", mapping.RiskIdentified)
	fmt.Printf("   - Critical Blocker → %s\n", mapping.CriticalBlocker)
	fmt.Printf("   - Priority Change → %s\n", mapping.PriorityChange)
	fmt.Printf("   - Access Request → %s\n", mapping.AccessRequest)
	fmt.Printf("   - Architecture Decision → %s\n", mapping.ArchitectureDecision)
	fmt.Printf("   - Information Share → %s\n", mapping.InformationShare)
	
	fmt.Println("\n🔤 Keyword Mappings:")
	fmt.Printf("   - Approval Keywords: %v\n", mapping.ApprovalKeywords)
	fmt.Printf("   - Warning Keywords: %v\n", mapping.WarningKeywords)
	fmt.Printf("   - Blocker Keywords: %v\n", mapping.BlockerKeywords)
}

// Utility function to show configuration validation
func demonstrateConfigValidation() {
	fmt.Println("\n📋 Configuration Validation")
	
	// Valid configuration
	validConfig := config.GetDefaultSlurpConfig()
	validConfig.Enabled = true
	validConfig.BaseURL = "https://slurp.example.com"
	
	if err := config.ValidateSlurpConfig(validConfig); err != nil {
		fmt.Printf("❌ Valid config failed validation: %v\n", err)
	} else {
		fmt.Println("✅ Valid configuration passed validation")
	}
	
	// Invalid configuration
	invalidConfig := config.GetDefaultSlurpConfig()
	invalidConfig.Enabled = true
	invalidConfig.BaseURL = "" // Missing required field
	
	if err := config.ValidateSlurpConfig(invalidConfig); err != nil {
		fmt.Printf("✅ Invalid config correctly failed validation: %v\n", err)
	} else {
		fmt.Println("❌ Invalid config incorrectly passed validation")
	}
}