import { logger } from '../../utils/logger';

export interface AgentIssueReport {
  id?: string;
  agentId: string;
  tenantId?: string;
  traceId?: string;
  level: 'INFO' | 'WARNING' | 'ERROR' | 'FATAL';
  issueType?: 'performance' | 'logic' | 'integration' | 'security';
  severity?: 'low' | 'medium' | 'high' | 'critical';
  category?: string;
  attribution?: string;
  description?: string;
  rootCause?: string;
  mitigation?: string;
  fallbackPath?: string;
  suggestedFix?: string;
  status?: 'open' | 'investigating' | 'resolved';
  timestamp?: Date;
}

export class AgentSelfAwarenessService {
  private static instance: AgentSelfAwarenessService;
  private issues: Map<string, AgentIssueReport> = new Map();

  private constructor() {}

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

  async reportIssue(issue: Omit<AgentIssueReport, 'id' | 'timestamp'>): Promise<string> {
    const id = `ISSUE-${Date.now()}`;
    const report: AgentIssueReport = {
      id,
      ...issue,
      status: issue.status || 'open',
      timestamp: new Date()
    };
    
    this.issues.set(id, report);
    logger.info(`[AgentSelfAwareness] Issue reported: ${id} - ${issue.description || issue.rootCause}`);
    
    return id;
  }

  async getIssues(agentId?: string): Promise<AgentIssueReport[]> {
    const allIssues = Array.from(this.issues.values());
    if (agentId) {
      return allIssues.filter(issue => issue.agentId === agentId);
    }
    return allIssues;
  }

  async resolveIssue(issueId: string): Promise<boolean> {
    const issue = this.issues.get(issueId);
    if (issue) {
      issue.status = 'resolved';
      logger.info(`[AgentSelfAwareness] Issue resolved: ${issueId}`);
      return true;
    }
    return false;
  }

  async performSelfCheck(): Promise<{ healthy: boolean; issues: AgentIssueReport[] }> {
    logger.info('[AgentSelfAwareness] Performing self-check...');
    const issues = await this.getIssues();
    const unresolvedIssues = issues.filter(i => i.status !== 'resolved');
    
    return {
      healthy: unresolvedIssues.length === 0,
      issues: unresolvedIssues
    };
  }

  async getHealthStatus(): Promise<{
    status: 'healthy' | 'degraded' | 'critical';
    issues: AgentIssueReport[];
    lastCheck: Date;
  }> {
    const { healthy, issues } = await this.performSelfCheck();
    
    return {
      status: healthy ? 'healthy' : (issues.some(i => i.level === 'FATAL') ? 'critical' : 'degraded'),
      issues,
      lastCheck: new Date()
    };
  }
}

export default AgentSelfAwarenessService.getInstance();
