import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import {
  GovDetectionService as CoreGovDetectionService,
  syncAllData,
  setLogger,
  type DetectionResult,
  type OrganizationType,
  type ResponseTier,
  type ProxyType,
} from '@lilith/gov-detection';

export interface GovEnrichment {
  isGovernment: boolean;
  orgType: OrganizationType;
  responseTier: ResponseTier;
  proxyType: ProxyType;
  org: string | null;
  asn: number | null;
}

@Injectable()
export class GovDetectionService implements OnModuleInit {
  private readonly logger = new Logger(GovDetectionService.name);
  private detector: CoreGovDetectionService | null = null;

  async onModuleInit(): Promise<void> {
    setLogger({
      debug: (msg: string) => this.logger.debug(msg),
      info: (msg: string) => this.logger.log(msg),
      warn: (msg: string) => this.logger.warn(msg),
      error: (msg: string, err?: Error) => this.logger.error(msg, err?.stack),
    });

    try {
      const result = await syncAllData();
      const failed = result.sources.filter((s) => s.error);
      this.logger.log(
        `Gov detection data synced: ${result.sources.length - failed.length} sources loaded` +
          (failed.length ? `, ${failed.length} failed` : ''),
      );
      this.detector = new CoreGovDetectionService();
    } catch (err) {
      this.logger.error('Gov detection init failed — enrichment disabled', err as Error);
    }
  }

  async enrich(ip: string): Promise<GovEnrichment> {
    const allow = this.allow();
    if (!this.detector) return allow;

    let result: DetectionResult;
    try {
      result = await this.detector.detect({ ip });
    } catch {
      return allow;
    }

    return {
      isGovernment: result.responseTier !== 'ALLOW',
      orgType: result.organizationType,
      responseTier: result.responseTier,
      proxyType: result.ipIntelligence?.proxyType ?? 'NONE',
      org: result.ipIntelligence?.organizationName ?? null,
      asn: result.ipIntelligence?.asn?.asn ?? null,
    };
  }

  private allow(): GovEnrichment {
    return {
      isGovernment: false,
      orgType: 'NORMAL',
      responseTier: 'ALLOW',
      proxyType: 'NONE',
      org: null,
      asn: null,
    };
  }
}
