import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import * as fs from 'fs';
import { logError, logInfo, logWarn, withSpan } from '../../../telemetry/telemetry';

const WARN_PERCENT = Number(process.env.DISK_WARN_PERCENT ?? 80);
const CRITICAL_PERCENT = Number(process.env.DISK_CRITICAL_PERCENT ?? 90);

@Injectable()
export class DiskMonitorService implements OnApplicationBootstrap {
  onApplicationBootstrap(): void {
    void this.checkDiskUsage();
  }

  @Cron(CronExpression.EVERY_HOUR)
  async checkDiskUsage(): Promise<void> {
    const target = process.env.UPLOAD_PATH || process.cwd();

    await withSpan('DiskMonitor.checkDiskUsage', { 'disk.path': target }, async () => {
      let stats: fs.StatsFs;
      try {
        stats = await fs.promises.statfs(target);
      } catch (error) {
        logError('Surveillance disque : impossible de lire les statistiques du volume', {
          'disk.path': target,
          error: error instanceof Error ? error.message : String(error),
        });
        return;
      }

      const totalBytes = stats.blocks * stats.bsize;
      const freeBytes = stats.bavail * stats.bsize;
      const usedBytes = totalBytes - freeBytes;
      const usedPercent = totalBytes > 0 ? Math.round((usedBytes / totalBytes) * 100) : 0;

      const toGb = (bytes: number) => Math.round((bytes / 1024 ** 3) * 10) / 10;

      const attributes = {
        'disk.path': target,
        'disk.total_gb': toGb(totalBytes),
        'disk.used_gb': toGb(usedBytes),
        'disk.free_gb': toGb(freeBytes),
        'disk.used_percent': usedPercent,
      };

      if (usedPercent >= CRITICAL_PERCENT) {
        logError(
          `Disque CRITIQUE : ${usedPercent}% utilisé (${toGb(freeBytes)} Go libres sur ${toGb(totalBytes)} Go). ` +
            `Les uploads de photos risquent d'échouer ou de produire des fichiers tronqués. ` +
            `Libérer de l'espace ou agrandir le volume au plus vite.`,
          attributes,
        );
      } else if (usedPercent >= WARN_PERCENT) {
        logWarn(
          `Disque presque plein : ${usedPercent}% utilisé (${toGb(freeBytes)} Go libres sur ${toGb(totalBytes)} Go). ` +
            `Au-delà de ${CRITICAL_PERCENT}% le stockage des shootings sera menacé — prévoir un nettoyage.`,
          attributes,
        );
      } else {
        logInfo(
          `État du disque : ${usedPercent}% utilisé (${toGb(freeBytes)} Go libres sur ${toGb(totalBytes)} Go)`,
          attributes,
        );
      }
    });
  }
}
