import { Injectable, InternalServerErrorException, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { existsSync } from 'node:fs';
import { chromium, type Browser } from 'playwright';

export interface PdfOptions {
  /** Paper name Chromium understands — A4, Letter, Legal… */
  pageSize?: string;
  /** top,right,bottom,left in millimetres. */
  marginsMm?: string;
}

const DEFAULT_MARGINS = '12,12,12,12';

/**
 * Renders HTML to PDF with a headless Chromium.
 *
 * One browser is kept alive for the process and a fresh context is used per
 * document — launching Chromium costs ~300ms, which would be paid on every
 * preview otherwise. The browser is re-launched transparently if it dies.
 *
 * Which Chromium is used is configuration, not code, because the answer differs
 * per host: PDF_BROWSER_EXECUTABLE points at a binary, PDF_BROWSER_CHANNEL picks
 * an installed channel ('chrome', 'msedge'), and with neither set Playwright's
 * own download is used (`npx playwright install chromium`).
 */
@Injectable()
export class PdfService implements OnModuleDestroy {
  private readonly log = new Logger(PdfService.name);
  private browser: Browser | null = null;
  private launching: Promise<Browser> | null = null;

  constructor(private readonly config: ConfigService) {}

  async onModuleDestroy(): Promise<void> {
    await this.browser?.close().catch(() => undefined);
    this.browser = null;
  }

  /** Whether a browser is actually present, WITHOUT launching one.
   *
   *  `npm ci` installs the playwright package but not the browser behind it —
   *  there is no postinstall — so a deploy that never runs `playwright install`
   *  produces an API that boots, answers /health, serves every screen, and then
   *  fails on the first debit note anybody tries to print. This is what lets a
   *  deploy find that out at deploy time. Resolving the path is a pure lookup;
   *  it costs nothing, so it is safe on a health endpoint.
   */
  rendererStatus(): { ok: boolean; source: string; detail?: string } {
    const executablePath = this.config.get<string>('PDF_BROWSER_EXECUTABLE') || undefined;
    if (executablePath) {
      return existsSync(executablePath)
        ? { ok: true, source: `executable:${executablePath}` }
        : { ok: false, source: `executable:${executablePath}`, detail: 'PDF_BROWSER_EXECUTABLE points at a file that is not there' };
    }
    const channel = this.config.get<string>('PDF_BROWSER_CHANNEL') || undefined;
    // A channel names a system browser Playwright locates at launch, so there is
    // nothing to stat here — report it and let the launch be the proof.
    if (channel) return { ok: true, source: `channel:${channel}` };
    try {
      const bundled = chromium.executablePath();
      return existsSync(bundled)
        ? { ok: true, source: 'bundled' }
        : { ok: false, source: 'bundled', detail: 'run: npx playwright install --with-deps chromium' };
    } catch (err) {
      return { ok: false, source: 'bundled', detail: err instanceof Error ? err.message.split('\n')[0] : String(err) };
    }
  }

  private async getBrowser(): Promise<Browser> {
    if (this.browser?.isConnected()) return this.browser;
    // Collapse concurrent first-hits onto one launch.
    this.launching ??= this.launch().finally(() => {
      this.launching = null;
    });
    this.browser = await this.launching;
    return this.browser;
  }

  private async launch(): Promise<Browser> {
    const executablePath = this.config.get<string>('PDF_BROWSER_EXECUTABLE') || undefined;
    const channel = this.config.get<string>('PDF_BROWSER_CHANNEL') || undefined;
    try {
      const browser = await chromium.launch({
        executablePath,
        channel: executablePath ? undefined : channel,
        // The sandbox needs kernel privileges many shared hosts don't grant, and
        // we only ever render our own HTML.
        args: ['--no-sandbox', '--disable-dev-shm-usage'],
      });
      this.log.log(`PDF renderer ready (${executablePath ?? channel ?? 'bundled chromium'})`);
      return browser;
    } catch (err) {
      const detail = err instanceof Error ? err.message.split('\n')[0] : String(err);
      this.log.error(`Could not start the PDF renderer: ${detail}`);
      throw new InternalServerErrorException(
        'The PDF renderer is not available on this server. Install a browser (npx playwright install --with-deps chromium) or set PDF_BROWSER_EXECUTABLE.',
      );
    }
  }

  /** Print a complete HTML document to PDF bytes. */
  async render(html: string, opts: PdfOptions = {}): Promise<Buffer> {
    const browser = await this.getBrowser();
    const context = await browser.newContext();
    try {
      const page = await context.newPage();
      // The HTML is fully self-contained (images inlined as data URIs), so
      // 'load' settles without waiting on a network that will never be used.
      await page.setContent(html, { waitUntil: 'load' });
      const [top, right, bottom, left] = (opts.marginsMm ?? DEFAULT_MARGINS).split(',').map((n) => `${Number(n.trim()) || 0}mm`);
      return await page.pdf({
        format: opts.pageSize || 'A4',
        printBackground: true,
        margin: { top, right, bottom, left },
      });
    } finally {
      await context.close().catch(() => undefined);
    }
  }
}
