/**
 * Monogram Badge Generator
 *
 * Generates 256x256 monogram badge PNGs for teams with no discoverable logo.
 * Uses the same HSL hash algorithm as the frontend TeamLogo component.
 */

import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { createCanvas } from 'canvas';
import { upsertLogoRecord } from '../models/logo';

const BADGE_SIZE = 256;

/** Hash team name to HSL hue — matches frontend getTeamColor */
function teamHue(teamName: string): number {
  let hash = 0;
  for (let i = 0; i < teamName.length; i++) {
    hash = teamName.charCodeAt(i) + ((hash << 5) - hash);
  }
  return Math.abs(hash) % 360;
}

/**
 * Generate a 256x256 monogram badge PNG and write to destPath.
 * Dark circular badge with HSL-hashed background, white bold abbreviation.
 */
export async function generateMonogramBadge(
  abbr: string,
  teamName: string,
  destPath: string
): Promise<{ success: boolean; checksum?: string; error?: string }> {
  try {
    const canvas = createCanvas(BADGE_SIZE, BADGE_SIZE);
    const ctx = canvas.getContext('2d');

    // Background: transparent
    ctx.clearRect(0, 0, BADGE_SIZE, BADGE_SIZE);

    // Circle fill with team-hue color
    const hue = teamHue(teamName);
    const cx = BADGE_SIZE / 2;
    const cy = BADGE_SIZE / 2;
    const radius = BADGE_SIZE / 2 - 4; // 4px padding

    ctx.beginPath();
    ctx.arc(cx, cy, radius, 0, Math.PI * 2);
    ctx.fillStyle = `hsl(${hue}, 45%, 30%)`;
    ctx.fill();

    // Subtle ring
    ctx.strokeStyle = `hsl(${hue}, 55%, 45%)`;
    ctx.lineWidth = 4;
    ctx.stroke();

    // Text: abbreviation (2-4 chars), white, centered
    const label = abbr.toUpperCase().slice(0, 4);
    const fontSize = label.length <= 2 ? 100 : label.length === 3 ? 80 : 64;
    ctx.font = `bold ${fontSize}px sans-serif`;
    ctx.fillStyle = '#FFFFFF';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(label, cx, cy + 2); // +2 for optical centering

    // Write to disk (atomic)
    const dir = path.dirname(destPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    const buf = canvas.toBuffer('image/png');
    const tmpPath = destPath + '.tmp';
    fs.writeFileSync(tmpPath, buf);
    fs.renameSync(tmpPath, destPath);

    const checksum = crypto.createHash('sha256').update(buf).digest('hex');
    return { success: true, checksum };
  } catch (err) {
    return { success: false, error: (err as Error).message };
  }
}

/**
 * Generate monogram and record in DB as fallback.
 */
export async function generateAndRecordMonogram(
  league: string,
  abbr: string,
  teamName: string,
  destPath: string,
  relativePath: string
): Promise<{ success: boolean; checksum?: string; error?: string }> {
  const result = await generateMonogramBadge(abbr, teamName, destPath);
  if (result.success) {
    await upsertLogoRecord(league, abbr, {
      team_name: teamName,
      file_path: relativePath,
      file_exists: true,
      checksum_sha256: result.checksum || null,
      source: 'monogram',
      resolution_status: 'fallback',
    });
  }
  return result;
}
