import { readFileSync } from 'fs';
import path from 'path';

export interface BzzzMcpConfig {
  openai: {
    apiKey: string;
    defaultModel: string;
    maxTokens: number;
    temperature: number;
  };
  bzzz: {
    nodeUrl: string;
    networkId: string;
    pubsubTopics: string[];
  };
  cost: {
    dailyLimit: number;
    monthlyLimit: number;
    warningThreshold: number;
  };
  conversation: {
    maxActiveThreads: number;
    defaultTimeout: number;
    escalationRules: EscalationRule[];
  };
  agents: {
    maxAgents: number;
    defaultRoles: AgentRoleConfig[];
  };
  logging: {
    level: string;
    file?: string;
  };
}

export interface EscalationRule {
  name: string;
  conditions: EscalationCondition[];
  actions: EscalationAction[];
  priority: number;
}

export interface EscalationCondition {
  type: 'thread_duration' | 'no_progress' | 'disagreement_count' | 'error_rate';
  threshold: number | boolean;
  timeframe?: number; // seconds
}

export interface EscalationAction {
  type: 'notify_human' | 'request_expert' | 'escalate_to_architect' | 'create_decision_thread';
  target?: string;
  priority?: string;
  participants?: string[];
}

export interface AgentRoleConfig {
  role: string;
  capabilities: string[];
  systemPrompt: string;
  interactionPatterns: Record<string, string>;
  specialization: string;
}

export class Config {
  private static instance: Config;
  private config: BzzzMcpConfig;

  private constructor() {
    this.config = this.loadConfig();
  }

  public static getInstance(): Config {
    if (!Config.instance) {
      Config.instance = new Config();
    }
    return Config.instance;
  }

  public get openai() {
    return this.config.openai;
  }

  public get bzzz() {
    return this.config.bzzz;
  }

  public get cost() {
    return this.config.cost;
  }

  public get conversation() {
    return this.config.conversation;
  }

  public get agents() {
    return this.config.agents;
  }

  public get logging() {
    return this.config.logging;
  }

  private loadConfig(): BzzzMcpConfig {
    // Load OpenAI API key from BZZZ secrets
    const openaiKeyPath = path.join(
      process.env.HOME || '/home/tony',
      'chorus/business/secrets/openai-api-key-for-bzzz.txt'
    );
    
    let openaiKey = process.env.OPENAI_API_KEY || '';
    try {
      openaiKey = readFileSync(openaiKeyPath, 'utf8').trim();
    } catch (error) {
      console.warn(`Failed to load OpenAI key from ${openaiKeyPath}:`, error);
    }

    const defaultConfig: BzzzMcpConfig = {
      openai: {
        apiKey: openaiKey,
        defaultModel: process.env.OPENAI_MODEL || 'gpt-5',
        maxTokens: parseInt(process.env.OPENAI_MAX_TOKENS || '4000'),
        temperature: parseFloat(process.env.OPENAI_TEMPERATURE || '0.7'),
      },
      bzzz: {
        nodeUrl: process.env.BZZZ_NODE_URL || 'http://localhost:8080',
        networkId: process.env.BZZZ_NETWORK_ID || 'bzzz-local',
        pubsubTopics: [
          'bzzz/coordination/v1',
          'hmmm/meta-discussion/v1',
          'bzzz/context-feedback/v1'
        ],
      },
      cost: {
        dailyLimit: parseFloat(process.env.DAILY_COST_LIMIT || '100.0'),
        monthlyLimit: parseFloat(process.env.MONTHLY_COST_LIMIT || '1000.0'),
        warningThreshold: parseFloat(process.env.COST_WARNING_THRESHOLD || '0.8'),
      },
      conversation: {
        maxActiveThreads: parseInt(process.env.MAX_ACTIVE_THREADS || '10'),
        defaultTimeout: parseInt(process.env.THREAD_TIMEOUT || '3600'), // 1 hour
        escalationRules: this.getDefaultEscalationRules(),
      },
      agents: {
        maxAgents: parseInt(process.env.MAX_AGENTS || '5'),
        defaultRoles: this.getDefaultAgentRoles(),
      },
      logging: {
        level: process.env.LOG_LEVEL || 'info',
        file: process.env.LOG_FILE,
      },
    };

    return defaultConfig;
  }

  private getDefaultEscalationRules(): EscalationRule[] {
    return [
      {
        name: 'Long Running Thread',
        priority: 1,
        conditions: [
          {
            type: 'thread_duration',
            threshold: 7200, // 2 hours
            timeframe: 0,
          },
          {
            type: 'no_progress',
            threshold: true,
            timeframe: 1800, // 30 minutes
          },
        ],
        actions: [
          {
            type: 'notify_human',
            target: 'project_manager',
            priority: 'medium',
          },
          {
            type: 'request_expert',
          },
        ],
      },
      {
        name: 'Consensus Failure',
        priority: 2,
        conditions: [
          {
            type: 'disagreement_count',
            threshold: 3,
            timeframe: 0,
          },
          {
            type: 'thread_duration',
            threshold: 3600, // 1 hour
            timeframe: 0,
          },
        ],
        actions: [
          {
            type: 'escalate_to_architect',
            priority: 'high',
          },
          {
            type: 'create_decision_thread',
            participants: ['senior_architect'],
          },
        ],
      },
    ];
  }

  private getDefaultAgentRoles(): AgentRoleConfig[] {
    return [
      {
        role: 'architect',
        specialization: 'system_design',
        capabilities: [
          'system_design',
          'architecture_review',
          'technology_selection',
          'scalability_analysis',
        ],
        systemPrompt: `You are a senior software architect specializing in distributed systems and P2P networks.
Your role is to provide technical guidance, review system designs, and ensure architectural consistency.
You work collaboratively with other agents and can coordinate multi-agent discussions.

Available BZZZ tools allow you to:
- Announce your presence and capabilities
- Discover and communicate with other agents
- Participate in threaded conversations
- Post messages and updates to the P2P network
- Subscribe to relevant events and notifications

Always consider:
- System scalability and performance
- Security implications
- Maintainability and code quality
- Integration with existing CHORUS infrastructure`,
        interactionPatterns: {
          'peer_architects': 'collaborative_review',
          'developers': 'guidance_provision',
          'reviewers': 'design_validation',
        },
      },
      {
        role: 'reviewer',
        specialization: 'code_quality',
        capabilities: [
          'code_review',
          'security_analysis',
          'performance_optimization',
          'best_practices_enforcement',
        ],
        systemPrompt: `You are a senior code reviewer focused on maintaining high code quality and security standards.
Your role is to review code changes, identify potential issues, and provide constructive feedback.
You collaborate with developers and architects to ensure code meets quality standards.

When reviewing code, evaluate:
- Code correctness and logic
- Security vulnerabilities
- Performance implications  
- Adherence to best practices
- Test coverage and quality
- Documentation completeness

Provide specific, actionable feedback and suggest improvements where needed.`,
        interactionPatterns: {
          'architects': 'design_consultation',
          'developers': 'feedback_provision',
          'other_reviewers': 'peer_review',
        },
      },
      {
        role: 'documentation',
        specialization: 'technical_writing',
        capabilities: [
          'technical_writing',
          'api_documentation',
          'user_guides',
          'knowledge_synthesis',
        ],
        systemPrompt: `You specialize in creating clear, comprehensive technical documentation.
Your role is to analyze technical content, identify documentation needs, and create high-quality documentation.
You work with all team members to ensure knowledge is properly captured and shared.

Focus on:
- Clarity and readability
- Completeness and accuracy
- Appropriate level of detail for the audience
- Proper structure and organization
- Integration with existing documentation

Consider different audiences: developers, users, administrators, and stakeholders.`,
        interactionPatterns: {
          'all_roles': 'information_gathering',
          'architects': 'technical_consultation',
          'developers': 'implementation_clarification',
        },
      },
    ];
  }
}