import { BadRequestException, Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { randomUUID } from 'crypto';
import sharp from 'sharp';
import { envs } from 'src/config/envs';
import { PrismaService } from 'src/prisma/prisma.service';
import { AuditService } from 'src/audit/audit.service';

/**
 * Imagen de firma y sello de los recibos (`docs/plan-firma-recibos.md` §9): una firma manuscrita escaneada o una foto
 * que va impresa en el recuadro «Firma y sello» de los recibos A4. No es una firma digital; convive con ella.
 *
 * Se guarda en Spaces con ACL privada (cualquiera con la URL pública podría copiar la firma): se muestra con URL
 * firmada de corta duración y al generador se le pasa la imagen misma.
 */

export const MAX_BYTES_FIRMA = 5 * 1024 * 1024;
const TIPOS = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/webp']);
/** Tamaño máximo con que se guarda: el recuadro del recibo mide ~170×70 pt; 800 px alcanzan para imprimir nítido. */
const ANCHO_MAX = 800;
const ALTO_MAX = 400;
const URL_SEG = 600;
const CACHE_MS = 30 * 60 * 1000;
const CACHE_MAX = 200;

/** Desde cuánto se considera que la imagen ya viene recortada (fondo transparente): 5 % de píxeles transparentes. */
const YA_TRANSPARENTE = 0.05;
/** El papel es claro: si el tono que domina es más oscuro, no hay papel que sacar (imagen oscura o casi toda tinta). */
const PAPEL_MINIMO = 140;
/** Si después de sacar el fondo queda visible menos que esto, se habría borrado la firma: va la imagen como vino. */
const VISIBLE_MINIMO = 0.005;

/**
 * Vuelve transparente el papel: la foto de una firma sobre una hoja trae el fondo gris o crema (luz, sombra) y en el
 * recibo se vería un rectángulo. El tono del papel se estima por la imagen misma (los píxeles más claros, que son la
 * mayoría); lo que está cerca de ese tono se vuelve transparente y la tinta y el sello quedan opacos, con su color.
 *
 * No se toca la imagen (va como vino) cuando:
 *  - ya trae el fondo transparente (un PNG recortado): ahí lo visible es solo la tinta y se la confundiría con el papel;
 *  - no hay un papel claro que domine;
 *  - el resultado dejaría la firma prácticamente vacía.
 */
export async function quitarFondo(entrada: Buffer): Promise<Buffer> {
  const { data, info } = await sharp(entrada).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
  const n = info.width * info.height;
  let transparentes = 0;
  for (let i = 0; i < n; i++) if (data[i * 4 + 3] < 128) transparentes++;
  if (transparentes > n * YA_TRANSPARENTE) return entrada;

  const lum = new Uint8Array(n);
  const hist = new Uint32Array(256);
  for (let i = 0; i < n; i++) {
    const o = i * 4;
    const l = Math.round(0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2]);
    lum[i] = l;
    hist[l]++;
  }
  // Tono del papel: percentil 85 de la luminosidad.
  let acum = 0;
  let papel = 255;
  for (let l = 0; l < 256; l++) {
    acum += hist[l];
    if (acum >= n * 0.85) {
      papel = l;
      break;
    }
  }
  if (papel < PAPEL_MINIMO) return entrada;

  const claro = papel - 25; // desde acá, transparente
  const oscuro = papel - 90; // hasta acá, opaco; en el medio, gradual (bordes del trazo suaves)
  const salida = Buffer.from(data);
  let visibles = 0;
  for (let i = 0; i < n; i++) {
    const l = lum[i];
    const a = Math.min(data[i * 4 + 3], l >= claro ? 0 : l <= oscuro ? 255 : Math.round(((claro - l) / (claro - oscuro)) * 255));
    salida[i * 4 + 3] = a;
    if (a >= 128) visibles++;
  }
  if (visibles < n * VISIBLE_MINIMO) return entrada;
  return sharp(salida, { raw: { width: info.width, height: info.height, channels: 4 } }).png().toBuffer();
}

/**
 * Prepara la imagen para el recibo: la gira según el EXIF (foto del celular), vuelve transparente el papel, recorta
 * el borde vacío para que la firma ocupe el recuadro y la achica. Siempre sale PNG con transparencia.
 */
export async function normalizarImagenFirma(origen: Buffer): Promise<Buffer> {
  let base: Buffer;
  try {
    // Primero un tamaño de trabajo razonable: una foto de 12 MP no hace falta para un recuadro de 170 pt.
    base = await sharp(origen).rotate().resize({ width: 1600, height: 1600, fit: 'inside', withoutEnlargement: true }).toBuffer();
  } catch {
    throw new BadRequestException('No se pudo leer la imagen. Probá con un PNG o JPG.');
  }
  const sinFondo = await quitarFondo(base);
  // El recorte toma el color del borde como fondo: solo se hace si el fondo quedó transparente (si no, con una esquina
  // de tinta se recortaría la firma).
  let recortada = sinFondo;
  if (await tieneTransparencia(sinFondo)) {
    try {
      recortada = await sharp(sinFondo).trim({ threshold: 10 }).toBuffer();
    } catch {
      // trim falla si no queda nada distinto del borde: sin recorte.
    }
  }
  const lista = await sharp(recortada)
    .resize({ width: ANCHO_MAX, height: ALTO_MAX, fit: 'inside', withoutEnlargement: true })
    .png({ compressionLevel: 9, palette: true })
    .toBuffer();
  if (await estaVacia(lista)) {
    throw new BadRequestException('En la imagen no se ve ninguna firma. Probá con una foto de la firma y el sello sobre papel blanco.');
  }
  return lista;
}

async function tieneTransparencia(imagen: Buffer): Promise<boolean> {
  const { data, info } = await sharp(imagen).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
  for (let i = 0; i < info.width * info.height; i++) if (data[i * 4 + 3] < 128) return true;
  return false;
}

/** Sin nada que se vea: toda transparente, o toda clara (una hoja en blanco). Así no se guarda un recuadro vacío. */
export async function estaVacia(imagen: Buffer): Promise<boolean> {
  const { data, info } = await sharp(imagen).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
  const n = info.width * info.height;
  let tinta = 0;
  for (let i = 0; i < n; i++) {
    const o = i * 4;
    const l = 0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2];
    if (data[o + 3] >= 128 && l < 200) tinta++;
  }
  return tinta < Math.max(1, n * 0.001);
}

@Injectable()
export class FirmaImagenService {
  private readonly log = new Logger(FirmaImagenService.name);
  private readonly client = new S3Client({
    endpoint: envs.doSpacesEndpoint,
    region: envs.doSpacesRegion,
    credentials: { accessKeyId: envs.doSpacesKey, secretAccessKey: envs.doSpacesSecret },
  });
  /** clave → imagen en base64, para no bajarla de Spaces en cada recibo. La clave cambia con cada subida. */
  private readonly cache = new Map<string, { base64: string; vence: number }>();

  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
  ) {}

  private async clave(empresaId: string): Promise<string | null> {
    const e = await this.prisma.empresas.findUnique({ where: { id: empresaId }, select: { recibo_firma_imagen_key: true } });
    return e?.recibo_firma_imagen_key ?? null;
  }

  /** Lo que ve la pantalla: la imagen con URL firmada de 10 min, o null si no hay. */
  async ver(empresaId: string): Promise<{ url: string | null }> {
    const key = await this.clave(empresaId);
    if (!key) return { url: null };
    try {
      return { url: await getSignedUrl(this.client, new GetObjectCommand({ Bucket: envs.doSpacesBucket, Key: key }), { expiresIn: URL_SEG }) };
    } catch (err) {
      this.log.warn(`No se pudo firmar la URL de la firma de recibos (${empresaId}): ${(err as Error)?.message}`);
      throw new InternalServerErrorException('No se pudo cargar la imagen de la firma. Recargá en unos minutos.');
    }
  }

  async subir(empresaId: string, archivo: { buffer?: Buffer; size?: number; mimetype?: string } | undefined, userId?: string) {
    if (!archivo?.buffer) throw new BadRequestException('Elegí una imagen');
    if ((archivo.size ?? archivo.buffer.length) > MAX_BYTES_FIRMA) throw new BadRequestException('La imagen pesa más de 5 MB');
    if (!archivo.mimetype || !TIPOS.has(archivo.mimetype)) throw new BadRequestException('Solo imágenes PNG, JPG o WEBP');
    const cuerpo = await normalizarImagenFirma(archivo.buffer);
    const key = `empresas/${empresaId}/firma-recibo-${randomUUID()}.png`;
    try {
      await this.client.send(
        new PutObjectCommand({ Bucket: envs.doSpacesBucket, Key: key, Body: cuerpo, ContentType: 'image/png', ACL: 'private', Metadata: { empresa_id: empresaId } }),
      );
    } catch (err) {
      this.log.error(`No se pudo subir ${key}: ${(err as Error)?.message}`);
      throw new InternalServerErrorException('No se pudo guardar la imagen. Probá de nuevo.');
    }
    await this.prisma.empresas.update({ where: { id: empresaId }, data: { recibo_firma_imagen_key: key, updated_at: new Date() } });
    this.cache.set(key, { base64: cuerpo.toString('base64'), vence: Date.now() + CACHE_MS });
    await this.audit.log({
      empresa_id: empresaId,
      user_id: userId,
      action: 'UPDATE',
      entity_type: 'empresa',
      entity_id: empresaId,
      descripcion: 'Imagen de firma y sello de los recibos cargada',
    });
    return this.ver(empresaId);
  }

  /** Deja de imprimirse en los recibos. El archivo queda en Spaces (no se borra nada). */
  async quitar(empresaId: string, userId?: string) {
    await this.prisma.empresas.update({ where: { id: empresaId }, data: { recibo_firma_imagen_key: null, updated_at: new Date() } });
    await this.audit.log({
      empresa_id: empresaId,
      user_id: userId,
      action: 'UPDATE',
      entity_type: 'empresa',
      entity_id: empresaId,
      descripcion: 'Imagen de firma y sello de los recibos quitada',
    });
    return { url: null };
  }

  /**
   * La imagen en base64 para el generador, o null. Nunca lanza: si Spaces no responde, el recibo sale igual sin la
   * imagen (no se frena la cobranza por la firma).
   */
  async paraRecibo(key: string | null | undefined): Promise<string | null> {
    if (!key) return null;
    const hit = this.cache.get(key);
    if (hit && hit.vence > Date.now()) return hit.base64;
    try {
      const r = await this.client.send(new GetObjectCommand({ Bucket: envs.doSpacesBucket, Key: key }));
      const bytes = await r.Body?.transformToByteArray();
      if (!bytes?.length) return null;
      const base64 = Buffer.from(bytes).toString('base64');
      if (this.cache.size >= CACHE_MAX) this.cache.delete(this.cache.keys().next().value as string);
      this.cache.set(key, { base64, vence: Date.now() + CACHE_MS });
      return base64;
    } catch (err) {
      this.log.warn(`Recibo sin imagen de firma: no se pudo bajar ${key} (${(err as Error)?.name})`);
      return null;
    }
  }
}
