import pino from 'pino';

const logger = pino({ name: 'discovery-aws' });

export interface DiscoveredService {
  name: string;
  type: string;           // 'ecs-service', 'lambda', 'rds', 'ec2', etc.
  arn: string;
  region: string;
  account: string;
  tags: Record<string, string>;
  owner?: string;         // From tags or CODEOWNERS
  ownerSource?: 'aws-tag' | 'codeowners' | 'config' | 'heuristic';
  metadata: Record<string, any>;
  discoveredAt: Date;
}

export interface ScanResult {
  status: 'success' | 'partial_failure' | 'failed';
  discovered: number;
  errors: string[];
  services: DiscoveredService[];
}

/**
 * AWS Discovery Scanner.
 * Scans ECS services, Lambda functions, RDS instances.
 * Partial failures preserve existing catalog (BMad must-have).
 */
export class AwsDiscoveryScanner {
  private ecsClient: any;
  private lambdaClient: any;
  private rdsClient: any;

  constructor(clients: { ecs: any; lambda: any; rds: any }) {
    this.ecsClient = clients.ecs;
    this.lambdaClient = clients.lambda;
    this.rdsClient = clients.rds;
  }

  async scan(region: string, account: string): Promise<ScanResult> {
    const services: DiscoveredService[] = [];
    const errors: string[] = [];

    // Scan ECS
    try {
      const ecsServices = await this.scanEcs(region, account);
      services.push(...ecsServices);
    } catch (err) {
      errors.push(`ECS scan failed: ${(err as Error).message}`);
      logger.warn({ region, error: (err as Error).message }, 'ECS scan failed');
    }

    // Scan Lambda
    try {
      const lambdaFns = await this.scanLambda(region, account);
      services.push(...lambdaFns);
    } catch (err) {
      errors.push(`Lambda scan failed: ${(err as Error).message}`);
      logger.warn({ region, error: (err as Error).message }, 'Lambda scan failed');
    }

    // Scan RDS
    try {
      const rdsInstances = await this.scanRds(region, account);
      services.push(...rdsInstances);
    } catch (err) {
      errors.push(`RDS scan failed: ${(err as Error).message}`);
      logger.warn({ region, error: (err as Error).message }, 'RDS scan failed');
    }

    const status = errors.length === 0
      ? 'success'
      : services.length > 0
        ? 'partial_failure'
        : 'failed';

    return { status, discovered: services.length, errors, services };
  }

  private async scanEcs(region: string, account: string): Promise<DiscoveredService[]> {
    // TODO: List clusters → list services → describe services → extract tags
    return [];
  }

  private async scanLambda(region: string, account: string): Promise<DiscoveredService[]> {
    // TODO: List functions → get tags → map to DiscoveredService
    return [];
  }

  private async scanRds(region: string, account: string): Promise<DiscoveredService[]> {
    // TODO: Describe DB instances → extract tags
    return [];
  }
}
