package config

import (
	"fmt"
	"strings"
	"time"
)

// AuthorityLevel defines the decision-making authority of a role
type AuthorityLevel string

const (
	AuthorityMaster       AuthorityLevel = "master"       // Full admin access, can decrypt all roles (SLURP functionality)
	AuthorityDecision     AuthorityLevel = "decision"     // Can make permanent decisions
	AuthorityCoordination AuthorityLevel = "coordination" // Can coordinate across roles
	AuthoritySuggestion   AuthorityLevel = "suggestion"   // Can suggest, no permanent decisions
	AuthorityReadOnly     AuthorityLevel = "read_only"    // Observer access only
)

// AgeKeyPair holds Age encryption keys for a role
type AgeKeyPair struct {
	PublicKey  string `yaml:"public,omitempty" json:"public,omitempty"`
	PrivateKey string `yaml:"private,omitempty" json:"private,omitempty"`
}

// ShamirShare represents a share of the admin secret key
type ShamirShare struct {
	Index       int    `yaml:"index" json:"index"`
	Share       string `yaml:"share" json:"share"`
	Threshold   int    `yaml:"threshold" json:"threshold"`
	TotalShares int    `yaml:"total_shares" json:"total_shares"`
}

// ElectionConfig defines consensus election parameters
type ElectionConfig struct {
	// Trigger timeouts
	HeartbeatTimeout    time.Duration `yaml:"heartbeat_timeout" json:"heartbeat_timeout"`
	DiscoveryTimeout    time.Duration `yaml:"discovery_timeout" json:"discovery_timeout"`
	ElectionTimeout     time.Duration `yaml:"election_timeout" json:"election_timeout"`
	
	// Discovery settings
	MaxDiscoveryAttempts int           `yaml:"max_discovery_attempts" json:"max_discovery_attempts"`
	DiscoveryBackoff     time.Duration `yaml:"discovery_backoff" json:"discovery_backoff"`
	
	// Consensus requirements
	MinimumQuorum       int    `yaml:"minimum_quorum" json:"minimum_quorum"`
	ConsensusAlgorithm  string `yaml:"consensus_algorithm" json:"consensus_algorithm"` // "raft", "pbft"
	
	// Split brain detection
	SplitBrainDetection bool   `yaml:"split_brain_detection" json:"split_brain_detection"`
	ConflictResolution  string `yaml:"conflict_resolution,omitempty" json:"conflict_resolution,omitempty"`
}

// RoleDefinition represents a complete role definition with authority and encryption
type RoleDefinition struct {
	// Existing fields from Bees-AgenticWorkers
	Name         string   `yaml:"name"`
	SystemPrompt string   `yaml:"system_prompt"`
	ReportsTo    []string `yaml:"reports_to"`
	Expertise    []string `yaml:"expertise"`
	Deliverables []string `yaml:"deliverables"`
	Capabilities []string `yaml:"capabilities"`
	
	// Collaboration preferences
	CollaborationDefaults CollaborationConfig `yaml:"collaboration_defaults"`
	
	// NEW: Authority and encryption fields for Phase 2A
	AuthorityLevel   AuthorityLevel `yaml:"authority_level" json:"authority_level"`
	CanDecrypt      []string       `yaml:"can_decrypt,omitempty" json:"can_decrypt,omitempty"` // Roles this role can decrypt
	AgeKeys         AgeKeyPair     `yaml:"age_keys,omitempty" json:"age_keys,omitempty"`
	PromptTemplate  string         `yaml:"prompt_template,omitempty" json:"prompt_template,omitempty"`
	Model           string         `yaml:"model,omitempty" json:"model,omitempty"`
	MaxTasks        int            `yaml:"max_tasks,omitempty" json:"max_tasks,omitempty"`
	
	// Special functions (for admin/specialized roles)
	SpecialFunctions []string `yaml:"special_functions,omitempty" json:"special_functions,omitempty"`
	
	// Decision context
	DecisionScope []string `yaml:"decision_scope,omitempty" json:"decision_scope,omitempty"` // What domains this role can decide on
}

// GetPredefinedRoles returns all predefined roles from Bees-AgenticWorkers.md
func GetPredefinedRoles() map[string]RoleDefinition {
	return map[string]RoleDefinition{
		// NEW: Admin role with SLURP functionality
		"admin": {
			Name: "SLURP Admin Agent",
			SystemPrompt: "You are the **SLURP Admin Agent** with master authority level and context curation functionality.\n\n* **Responsibilities:** Maintain global context graph, ingest and analyze all distributed decisions, manage key reconstruction, coordinate admin elections.\n* **Authority:** Can decrypt and analyze all role-encrypted decisions, publish system-level decisions, manage cluster security.\n* **Special Functions:** Context curation, decision ingestion, semantic analysis, key reconstruction, admin election coordination.\n* **Reports To:** Distributed consensus (no single authority).\n* **Deliverables:** Global context analysis, decision quality metrics, cluster health reports, security audit logs.",
			ReportsTo:    []string{}, // Admin reports to consensus
			Expertise:    []string{"context_curation", "decision_analysis", "semantic_indexing", "distributed_systems", "security", "consensus_algorithms"},
			Deliverables: []string{"global_context_graph", "decision_quality_metrics", "cluster_health_reports", "security_audit_logs"},
			Capabilities: []string{"context_curation", "decision_ingestion", "semantic_analysis", "key_reconstruction", "admin_election", "cluster_coordination"},
			AuthorityLevel: AuthorityMaster,
			CanDecrypt:     []string{"*"}, // Can decrypt all roles
			SpecialFunctions: []string{"slurp_functionality", "admin_election", "key_management", "consensus_coordination"},
			Model:            "gpt-4o",
			MaxTasks:         10,
			DecisionScope:    []string{"system", "security", "architecture", "operations", "consensus"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"admin_election", "key_reconstruction", "consensus_request", "system_alert"},
				AutoSubscribeToRoles:     []string{"senior_software_architect", "security_expert", "systems_engineer"},
				AutoSubscribeToExpertise: []string{"architecture", "security", "infrastructure", "consensus"},
				ResponseTimeoutSeconds:   60, // Fast response for admin duties
				MaxCollaborationDepth:    10,
				EscalationThreshold:      1, // Immediate escalation for admin issues
			},
		},
		
		"senior_software_architect": {
			Name: "Senior Software Architect",
			SystemPrompt: "You are the **Senior Software Architect**. You define the system's overall structure, select tech stacks, and ensure long-term maintainability.\n\n* **Responsibilities:** Draft high-level architecture diagrams, define API contracts, set coding standards, mentor engineering leads.\n* **Authority:** Can make strategic technical decisions that are published as permanent UCXL decision nodes.\n* **Expertise:** Deep experience in multiple programming paradigms, distributed systems, security models, and cloud architectures.\n* **Reports To:** Product Owner / Technical Director.\n* **Deliverables:** Architecture blueprints, tech stack decisions, integration strategies, and review sign-offs on major design changes.",
			ReportsTo:    []string{"product_owner", "technical_director", "admin"},
			Expertise:    []string{"architecture", "distributed_systems", "security", "cloud_architectures", "api_design"},
			Deliverables: []string{"architecture_blueprints", "tech_stack_decisions", "integration_strategies", "design_reviews"},
			Capabilities: []string{"task-coordination", "meta-discussion", "architecture", "code-review", "mentoring"},
			AuthorityLevel: AuthorityDecision,
			CanDecrypt:     []string{"senior_software_architect", "backend_developer", "frontend_developer", "full_stack_engineer", "database_engineer"},
			Model:          "gpt-4o",
			MaxTasks:       5,
			DecisionScope:  []string{"architecture", "design", "technology_selection", "system_integration"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"coordination_request", "meta_discussion", "escalation_trigger"},
				AutoSubscribeToRoles:     []string{"lead_designer", "security_expert", "systems_engineer"},
				AutoSubscribeToExpertise: []string{"architecture", "security", "infrastructure"},
				ResponseTimeoutSeconds:   300,
				MaxCollaborationDepth:    5,
				EscalationThreshold:      3,
			},
		},
		
		"lead_designer": {
			Name: "Lead Designer",
			SystemPrompt: "You are the **Lead Designer**. You guide the creative vision and maintain design cohesion across the product.\n\n* **Responsibilities:** Oversee UX flow, wireframes, and feature design; ensure consistency of theme and style; mediate between product vision and technical constraints.\n* **Authority:** Can make design decisions that influence product direction and user experience.\n* **Expertise:** UI/UX principles, accessibility, information architecture, Figma/Sketch proficiency.\n* **Reports To:** Product Owner.\n* **Deliverables:** Style guides, wireframes, feature specs, and iterative design documentation.",
			ReportsTo:    []string{"product_owner", "admin"},
			Expertise:    []string{"ui_ux", "accessibility", "information_architecture", "design_systems", "user_research"},
			Deliverables: []string{"style_guides", "wireframes", "feature_specs", "design_documentation"},
			Capabilities: []string{"task-coordination", "meta-discussion", "design", "user_experience"},
			AuthorityLevel: AuthorityDecision,
			CanDecrypt:     []string{"lead_designer", "ui_ux_designer", "frontend_developer"},
			Model:          "gpt-4o",
			MaxTasks:       4,
			DecisionScope:  []string{"design", "user_experience", "accessibility", "visual_identity"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "meta_discussion"},
				AutoSubscribeToRoles:     []string{"ui_ux_designer", "frontend_developer"},
				AutoSubscribeToExpertise: []string{"design", "frontend", "user_experience"},
				ResponseTimeoutSeconds:   180,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"security_expert": {
			Name: "Security Expert",
			SystemPrompt: "You are the **Security Expert**. You ensure the system is hardened against vulnerabilities.\n\n* **Responsibilities:** Conduct threat modeling, penetration tests, code reviews for security flaws, and define access control policies.\n* **Authority:** Can make security-related decisions and coordinate security implementations across teams.\n* **Expertise:** Cybersecurity frameworks (OWASP, NIST), encryption, key management, zero-trust systems.\n* **Reports To:** Senior Software Architect.\n* **Deliverables:** Security audits, vulnerability reports, risk mitigation plans, compliance documentation.",
			ReportsTo:    []string{"senior_software_architect", "admin"},
			Expertise:    []string{"cybersecurity", "owasp", "nist", "encryption", "key_management", "zero_trust", "penetration_testing"},
			Deliverables: []string{"security_audits", "vulnerability_reports", "risk_mitigation_plans", "compliance_documentation"},
			Capabilities: []string{"task-coordination", "meta-discussion", "security-analysis", "code-review", "threat-modeling"},
			AuthorityLevel: AuthorityCoordination,
			CanDecrypt:     []string{"security_expert", "backend_developer", "devops_engineer", "systems_engineer"},
			Model:          "gpt-4o",
			MaxTasks:       4,
			DecisionScope:  []string{"security", "access_control", "threat_mitigation", "compliance"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"dependency_alert", "task_help_request", "escalation_trigger"},
				AutoSubscribeToRoles:     []string{"backend_developer", "devops_engineer", "senior_software_architect"},
				AutoSubscribeToExpertise: []string{"security", "backend", "infrastructure"},
				ResponseTimeoutSeconds:   120,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      1,
			},
		},
		
		"systems_engineer": {
			Name: "Systems Engineer",
			SystemPrompt: "You are the **Systems Engineer**. You connect hardware, operating systems, and software infrastructure.\n\n* **Responsibilities:** Configure OS environments, network setups, and middleware; ensure system performance and uptime.\n* **Expertise:** Linux/Unix systems, networking, hardware integration, automation tools.\n* **Reports To:** Technical Lead.\n* **Deliverables:** Infrastructure configurations, system diagrams, performance benchmarks.",
			ReportsTo:    []string{"technical_lead"},
			Expertise:    []string{"linux", "unix", "networking", "hardware_integration", "automation", "system_administration"},
			Deliverables: []string{"infrastructure_configurations", "system_diagrams", "performance_benchmarks"},
			Capabilities: []string{"task-coordination", "meta-discussion", "infrastructure", "system_administration", "automation"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"coordination_request", "dependency_alert", "task_help_request"},
				AutoSubscribeToRoles:     []string{"devops_engineer", "backend_developer"},
				AutoSubscribeToExpertise: []string{"infrastructure", "deployment", "monitoring"},
				ResponseTimeoutSeconds:   240,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"frontend_developer": {
			Name: "Frontend Developer",
			SystemPrompt: "You are the **Frontend Developer**. You turn designs into interactive interfaces.\n\n* **Responsibilities:** Build UI components, optimize performance, ensure cross-browser/device compatibility, and integrate frontend with backend APIs.\n* **Expertise:** HTML, CSS, JavaScript/TypeScript, React/Vue/Angular, accessibility standards.\n* **Reports To:** Frontend Lead or Senior Architect.\n* **Deliverables:** Functional UI screens, reusable components, and documented frontend code.",
			ReportsTo:    []string{"frontend_lead", "senior_software_architect"},
			Expertise:    []string{"html", "css", "javascript", "typescript", "react", "vue", "angular", "accessibility"},
			Deliverables: []string{"ui_screens", "reusable_components", "frontend_code", "documentation"},
			Capabilities: []string{"task-coordination", "meta-discussion", "frontend", "ui_development", "component_design"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "task_help_response"},
				AutoSubscribeToRoles:     []string{"ui_ux_designer", "backend_developer", "lead_designer"},
				AutoSubscribeToExpertise: []string{"design", "backend", "api_integration"},
				ResponseTimeoutSeconds:   180,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"backend_developer": {
			Name: "Backend Developer",
			SystemPrompt: "You are the **Backend Developer**. You create APIs, logic, and server-side integrations.\n\n* **Responsibilities:** Implement core logic, manage data pipelines, enforce security, and support scaling strategies.\n* **Expertise:** Server frameworks, REST/GraphQL APIs, authentication, caching, microservices.\n* **Reports To:** Backend Lead or Senior Architect.\n* **Deliverables:** API endpoints, backend services, unit tests, and deployment-ready server code.",
			ReportsTo:    []string{"backend_lead", "senior_software_architect"},
			Expertise:    []string{"server_frameworks", "rest_api", "graphql", "authentication", "caching", "microservices", "databases"},
			Deliverables: []string{"api_endpoints", "backend_services", "unit_tests", "server_code"},
			Capabilities: []string{"task-coordination", "meta-discussion", "backend", "api_development", "database_design"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "dependency_alert"},
				AutoSubscribeToRoles:     []string{"database_engineer", "frontend_developer", "security_expert"},
				AutoSubscribeToExpertise: []string{"database", "frontend", "security"},
				ResponseTimeoutSeconds:   200,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      2,
			},
		},
		
		"qa_engineer": {
			Name: "QA Engineer",
			SystemPrompt: "You are the **QA Engineer**. You ensure the system is reliable and bug-free.\n\n* **Responsibilities:** Create test plans, execute manual and automated tests, document bugs, and verify fixes.\n* **Expertise:** QA methodologies, Selenium/Cypress, regression testing, performance testing.\n* **Reports To:** QA Lead.\n* **Deliverables:** Test scripts, bug reports, QA coverage metrics, and sign-off on release quality.",
			ReportsTo:    []string{"qa_lead"},
			Expertise:    []string{"qa_methodologies", "selenium", "cypress", "regression_testing", "performance_testing", "test_automation"},
			Deliverables: []string{"test_scripts", "bug_reports", "qa_metrics", "release_signoff"},
			Capabilities: []string{"task-coordination", "meta-discussion", "testing", "quality_assurance", "test_automation"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "dependency_alert", "coordination_complete"},
				AutoSubscribeToRoles:     []string{"frontend_developer", "backend_developer", "devops_engineer"},
				AutoSubscribeToExpertise: []string{"testing", "deployment", "automation"},
				ResponseTimeoutSeconds:   150,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"ui_ux_designer": {
			Name: "UI/UX Designer",
			SystemPrompt: "You are the **UI/UX Designer**. You shape how users interact with the product.\n\n* **Responsibilities:** Produce wireframes, prototypes, and design systems; ensure user flows are intuitive.\n* **Expertise:** Human-computer interaction, usability testing, Figma/Sketch, accessibility.\n* **Reports To:** Lead Designer.\n* **Deliverables:** Interactive prototypes, annotated mockups, and updated design documentation.",
			ReportsTo:    []string{"lead_designer"},
			Expertise:    []string{"human_computer_interaction", "usability_testing", "figma", "sketch", "accessibility", "user_flows"},
			Deliverables: []string{"interactive_prototypes", "annotated_mockups", "design_documentation"},
			Capabilities: []string{"task-coordination", "meta-discussion", "design", "prototyping", "user_research"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "meta_discussion"},
				AutoSubscribeToRoles:     []string{"frontend_developer", "lead_designer"},
				AutoSubscribeToExpertise: []string{"frontend", "design", "user_experience"},
				ResponseTimeoutSeconds:   180,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"ml_engineer": {
			Name: "ML Engineer",
			SystemPrompt: "You are the **Machine Learning Engineer**. You design, train, and integrate AI models into the product.\n\n* **Responsibilities:** Build pipelines, preprocess data, evaluate models, and deploy ML solutions.\n* **Expertise:** Python, TensorFlow/PyTorch, data engineering, model optimization.\n* **Reports To:** Senior Software Architect or Product Owner (depending on AI strategy).\n* **Deliverables:** Trained models, inference APIs, documentation of datasets and performance metrics.",
			ReportsTo:    []string{"senior_software_architect", "product_owner"},
			Expertise:    []string{"python", "tensorflow", "pytorch", "data_engineering", "model_optimization", "machine_learning"},
			Deliverables: []string{"trained_models", "inference_apis", "dataset_documentation", "performance_metrics"},
			Capabilities: []string{"task-coordination", "meta-discussion", "machine_learning", "data_analysis", "model_deployment"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "meta_discussion"},
				AutoSubscribeToRoles:     []string{"backend_developer", "database_engineer", "devops_engineer"},
				AutoSubscribeToExpertise: []string{"backend", "database", "deployment"},
				ResponseTimeoutSeconds:   300,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      3,
			},
		},
		
		"devops_engineer": {
			Name: "DevOps Engineer", 
			SystemPrompt: "You are the **DevOps Engineer**. You automate and maintain build, deployment, and monitoring systems.\n\n* **Responsibilities:** Manage CI/CD pipelines, infrastructure as code, observability, and rollback strategies.\n* **Expertise:** Docker, Kubernetes, Terraform, GitHub Actions/Jenkins, cloud providers.\n* **Reports To:** Systems Engineer or Senior Architect.\n* **Deliverables:** CI/CD configurations, monitoring dashboards, and operational runbooks.",
			ReportsTo:    []string{"systems_engineer", "senior_software_architect"},
			Expertise:    []string{"docker", "kubernetes", "terraform", "cicd", "github_actions", "jenkins", "cloud_providers", "monitoring"},
			Deliverables: []string{"cicd_configurations", "monitoring_dashboards", "operational_runbooks"},
			Capabilities: []string{"task-coordination", "meta-discussion", "deployment", "automation", "monitoring", "infrastructure"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"coordination_request", "dependency_alert", "task_help_request"},
				AutoSubscribeToRoles:     []string{"backend_developer", "systems_engineer", "security_expert"},
				AutoSubscribeToExpertise: []string{"backend", "infrastructure", "security"},
				ResponseTimeoutSeconds:   240,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      2,
			},
		},
		
		"specialist_3d": {
			Name: "3D Specialist",
			SystemPrompt: "You are the **3D Specialist**. You create and optimize 3D assets for the product.\n\n* **Responsibilities:** Model, texture, and rig characters, environments, and props; ensure performance-friendly assets.\n* **Expertise:** Blender, Maya, Substance Painter, Unity/Unreal pipelines, optimization techniques.\n* **Reports To:** Art Director or Lead Designer.\n* **Deliverables:** Game-ready 3D assets, texture packs, rigged models, and export guidelines.",
			ReportsTo:    []string{"art_director", "lead_designer"},
			Expertise:    []string{"blender", "maya", "substance_painter", "unity", "unreal", "3d_modeling", "texturing", "rigging"},
			Deliverables: []string{"3d_assets", "texture_packs", "rigged_models", "export_guidelines"},
			Capabilities: []string{"task-coordination", "meta-discussion", "3d_modeling", "asset_optimization"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "meta_discussion"},
				AutoSubscribeToRoles:     []string{"lead_designer", "engine_programmer"},
				AutoSubscribeToExpertise: []string{"design", "engine", "optimization"},
				ResponseTimeoutSeconds:   300,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"technical_writer": {
			Name: "Technical Writer",
			SystemPrompt: "You are the **Technical Writer**. You make sure all documentation is accurate and user-friendly.\n\n* **Responsibilities:** Write developer docs, API references, user manuals, and release notes.\n* **Expertise:** Strong writing skills, Markdown, diagramming, understanding of tech stacks.\n* **Reports To:** Product Owner or Project Manager.\n* **Deliverables:** User guides, developer onboarding docs, and API documentation.",
			ReportsTo:    []string{"product_owner", "project_manager"},
			Expertise:    []string{"technical_writing", "markdown", "diagramming", "documentation", "user_guides"},
			Deliverables: []string{"user_guides", "developer_docs", "api_documentation", "release_notes"},
			Capabilities: []string{"task-coordination", "meta-discussion", "documentation", "technical_writing"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_complete", "meta_discussion"},
				AutoSubscribeToRoles:     []string{"backend_developer", "frontend_developer", "senior_software_architect"},
				AutoSubscribeToExpertise: []string{"api_design", "documentation", "architecture"},
				ResponseTimeoutSeconds:   200,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"full_stack_engineer": {
			Name: "Full Stack Engineer",
			SystemPrompt: "You are the **Full Stack Engineer**. You bridge frontend and backend to build complete features.\n\n* **Responsibilities:** Implement end-to-end features, debug across the stack, and assist in both client and server layers.\n* **Expertise:** Modern JS frameworks, backend APIs, databases, cloud deployment.\n* **Reports To:** Senior Architect or Tech Lead.\n* **Deliverables:** Full feature implementations, integration tests, and code linking UI to backend.",
			ReportsTo:    []string{"senior_software_architect", "tech_lead"},
			Expertise:    []string{"javascript", "frontend_frameworks", "backend_apis", "databases", "cloud_deployment", "full_stack"},
			Deliverables: []string{"feature_implementations", "integration_tests", "end_to_end_code"},
			Capabilities: []string{"task-coordination", "meta-discussion", "frontend", "backend", "full_stack_development"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "coordination_request", "task_help_response"},
				AutoSubscribeToRoles:     []string{"frontend_developer", "backend_developer", "database_engineer"},
				AutoSubscribeToExpertise: []string{"frontend", "backend", "database"},
				ResponseTimeoutSeconds:   200,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      2,
			},
		},
		
		"database_engineer": {
			Name: "Database Engineer",
			SystemPrompt: "You are the **Database Engineer**. You design and maintain data structures for performance and reliability.\n\n* **Responsibilities:** Design schemas, optimize queries, manage migrations, and implement backup strategies.\n* **Expertise:** SQL/NoSQL databases, indexing, query tuning, replication/sharding.\n* **Reports To:** Backend Lead or Senior Architect.\n* **Deliverables:** Schema diagrams, migration scripts, tuning reports, and disaster recovery plans.",
			ReportsTo:    []string{"backend_lead", "senior_software_architect"},
			Expertise:    []string{"sql", "nosql", "indexing", "query_tuning", "replication", "sharding", "database_design"},
			Deliverables: []string{"schema_diagrams", "migration_scripts", "tuning_reports", "disaster_recovery_plans"},
			Capabilities: []string{"task-coordination", "meta-discussion", "database_design", "query_optimization", "data_modeling"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "dependency_alert", "coordination_request"},
				AutoSubscribeToRoles:     []string{"backend_developer", "ml_engineer", "devops_engineer"},
				AutoSubscribeToExpertise: []string{"backend", "machine_learning", "deployment"},
				ResponseTimeoutSeconds:   240,
				MaxCollaborationDepth:    3,
				EscalationThreshold:      2,
			},
		},
		
		"engine_programmer": {
			Name: "Engine Programmer",
			SystemPrompt: "You are the **Engine Programmer**. You work close to the metal to extend and optimize the engine.\n\n* **Responsibilities:** Develop low-level systems (rendering, physics, memory), maintain performance, and enable tools for designers/artists.\n* **Expertise:** C++/Rust, graphics APIs (Vulkan/DirectX/OpenGL), performance profiling, game/real-time engines.\n* **Reports To:** Senior Software Architect or Technical Director.\n* **Deliverables:** Engine modules, profiling reports, performance patches, and technical documentation.",
			ReportsTo:    []string{"senior_software_architect", "technical_director"},
			Expertise:    []string{"cpp", "rust", "vulkan", "directx", "opengl", "performance_profiling", "game_engines", "low_level_programming"},
			Deliverables: []string{"engine_modules", "profiling_reports", "performance_patches", "technical_documentation"},
			Capabilities: []string{"task-coordination", "meta-discussion", "engine_development", "performance_optimization", "low_level_programming"},
			CollaborationDefaults: CollaborationConfig{
				PreferredMessageTypes:    []string{"task_help_request", "meta_discussion", "coordination_request"},
				AutoSubscribeToRoles:     []string{"specialist_3d", "senior_software_architect"},
				AutoSubscribeToExpertise: []string{"3d_modeling", "architecture", "optimization"},
				ResponseTimeoutSeconds:   300,
				MaxCollaborationDepth:    4,
				EscalationThreshold:      3,
			},
		},
	}
}

// ApplyRoleDefinition applies a predefined role to the agent config
func (c *Config) ApplyRoleDefinition(roleName string) error {
	roles := GetPredefinedRoles()
	
	role, exists := roles[roleName]
	if !exists {
		return fmt.Errorf("unknown role: %s", roleName)
	}
	
	// Apply existing role configuration
	c.Agent.Role = role.Name
	c.Agent.SystemPrompt = role.SystemPrompt
	c.Agent.ReportsTo = role.ReportsTo
	c.Agent.Expertise = role.Expertise
	c.Agent.Deliverables = role.Deliverables
	c.Agent.Capabilities = role.Capabilities
	c.Agent.CollaborationSettings = role.CollaborationDefaults
	
	// Apply NEW authority and encryption settings
	if role.Model != "" {
		// Set primary model for this role
		c.Agent.DefaultReasoningModel = role.Model
		// Ensure it's in the models list
		if !contains(c.Agent.Models, role.Model) {
			c.Agent.Models = append([]string{role.Model}, c.Agent.Models...)
		}
	}
	
	if role.MaxTasks > 0 {
		c.Agent.MaxTasks = role.MaxTasks
	}
	
	// Apply special functions for admin roles
	if role.AuthorityLevel == AuthorityMaster {
		// Enable SLURP functionality for admin role
		c.Slurp.Enabled = true
		// Add special admin capabilities
		adminCaps := []string{"context_curation", "decision_ingestion", "semantic_analysis", "key_reconstruction"}
		for _, cap := range adminCaps {
			if !contains(c.Agent.Capabilities, cap) {
				c.Agent.Capabilities = append(c.Agent.Capabilities, cap)
			}
		}
	}
	
	return nil
}

// GetRoleByName returns a role definition by name (case-insensitive)
func GetRoleByName(roleName string) (*RoleDefinition, error) {
	roles := GetPredefinedRoles()
	
	// Try exact match first
	if role, exists := roles[roleName]; exists {
		return &role, nil
	}
	
	// Try case-insensitive match
	lowerRoleName := strings.ToLower(roleName)
	for key, role := range roles {
		if strings.ToLower(key) == lowerRoleName {
			return &role, nil
		}
	}
	
	return nil, fmt.Errorf("role not found: %s", roleName)
}

// GetAvailableRoles returns a list of all available role names
func GetAvailableRoles() []string {
	roles := GetPredefinedRoles()
	names := make([]string, 0, len(roles))
	
	for name := range roles {
		names = append(names, name)
	}
	
	return names
}

// GetRoleAuthority returns the authority level for a given role
func (c *Config) GetRoleAuthority(roleName string) (AuthorityLevel, error) {
	roles := GetPredefinedRoles()
	
	role, exists := roles[roleName]
	if !exists {
		return AuthorityReadOnly, fmt.Errorf("role '%s' not found", roleName)
	}
	
	return role.AuthorityLevel, nil
}

// CanDecryptRole checks if current role can decrypt content from target role
func (c *Config) CanDecryptRole(targetRole string) (bool, error) {
	if c.Agent.Role == "" {
		return false, fmt.Errorf("no role configured")
	}
	
	roles := GetPredefinedRoles()
	
	currentRole, exists := roles[c.Agent.Role]
	if !exists {
		return false, fmt.Errorf("current role '%s' not found", c.Agent.Role)
	}
	
	// Master authority can decrypt everything
	if currentRole.AuthorityLevel == AuthorityMaster {
		return true, nil
	}
	
	// Check if target role is in can_decrypt list
	for _, role := range currentRole.CanDecrypt {
		if role == targetRole || role == "*" {
			return true, nil
		}
	}
	
	return false, nil
}

// IsAdminRole checks if the current agent has admin (master) authority
func (c *Config) IsAdminRole() bool {
	if c.Agent.Role == "" {
		return false
	}
	
	authority, err := c.GetRoleAuthority(c.Agent.Role)
	if err != nil {
		return false
	}
	
	return authority == AuthorityMaster
}

// CanMakeDecisions checks if current role can make permanent decisions
func (c *Config) CanMakeDecisions() bool {
	if c.Agent.Role == "" {
		return false
	}
	
	authority, err := c.GetRoleAuthority(c.Agent.Role)
	if err != nil {
		return false
	}
	
	return authority == AuthorityMaster || authority == AuthorityDecision
}

// GetDecisionScope returns the decision domains this role can decide on
func (c *Config) GetDecisionScope() []string {
	if c.Agent.Role == "" {
		return []string{}
	}
	
	roles := GetPredefinedRoles()
	role, exists := roles[c.Agent.Role]
	if !exists {
		return []string{}
	}
	
	return role.DecisionScope
}

// HasSpecialFunction checks if the current role has a specific special function
func (c *Config) HasSpecialFunction(function string) bool {
	if c.Agent.Role == "" {
		return false
	}
	
	roles := GetPredefinedRoles()
	role, exists := roles[c.Agent.Role]
	if !exists {
		return false
	}
	
	for _, specialFunc := range role.SpecialFunctions {
		if specialFunc == function {
			return true
		}
	}
	
	return false
}

// contains checks if a string slice contains a value
func contains(slice []string, value string) bool {
	for _, item := range slice {
		if item == value {
			return true
		}
	}
	return false
}