import Phaser from 'phaser';
import { dollPlan, type DollPose } from './dollPlan';
import type { Patron } from '../data/types';

// Phaser half of the paper-doll renderer: paints a DollPlan into a cached
// texture. Contract (docs/CONTRACTS.md §5): callers get a texture key and never
// care whether the pixels came from procedural rects or real art.

export function dollTextureKey(p: Patron, pose: DollPose): string {
  // Drunk tells are baked into the texture, so intoxication stage is part of
  // the cache key (coarse: swayPx bucket, not raw float).
  return `doll:${p.dollSeed}:${pose}:${dollPlan(p, pose).swayPx}:${p.flags.disguised === true ? 'd' : ''}`;
}

export function renderDoll(scene: Phaser.Scene, p: Patron, pose: DollPose): string {
  const key = dollTextureKey(p, pose);
  if (scene.textures.exists(key)) return key;

  const plan = dollPlan(p, pose);
  const canvas = scene.textures.createCanvas(key, plan.width, plan.height);
  if (!canvas) return key; // key collision race — texture already exists
  const ctx = canvas.getContext();
  for (const r of plan.rects) {
    ctx.fillStyle = `#${r.colour.toString(16).padStart(6, '0')}`;
    ctx.fillRect(r.x, r.y, r.w, r.h);
  }
  canvas.refresh();
  return key;
}
