import { writeFileSync, mkdirSync } from 'fs';
import { resolve, dirname } from 'path';

const API_ENDPOINT = process.env.BANATIE_API_URL || 'https://api.banatie.com/v1/generate';
const API_KEY = process.env.BANATIE_API_KEY || '';

const PRESETS = {
  background: { width: 1200, height: 1700, format: 'png' },
  icon: { width: 128, height: 128, format: 'png', transparent: true },
};

export async function generateImage({ type = 'icon', prompt, output }) {
  if (!API_KEY) {
    console.error('BANATIE_API_KEY environment variable is not set');
    process.exit(1);
  }

  const preset = PRESETS[type];
  if (!preset) {
    console.error(`Unknown type: ${type}. Use "background" or "icon".`);
    process.exit(1);
  }

  const response = await fetch(API_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`,
    },
    body: JSON.stringify({
      prompt,
      ...preset,
    }),
  });

  if (!response.ok) {
    const body = await response.text();
    console.error(`API error ${response.status}: ${body}`);
    process.exit(1);
  }

  const buffer = Buffer.from(await response.arrayBuffer());
  const outputPath = resolve(output);
  mkdirSync(dirname(outputPath), { recursive: true });
  writeFileSync(outputPath, buffer);
  console.log(`Image saved: ${outputPath}`);
  return outputPath;
}

function parseArgs(args) {
  const result = {};
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--type') result.type = args[++i];
    else if (args[i] === '--prompt') result.prompt = args[++i];
    else if (args[i] === '--output') result.output = args[++i];
  }
  return result;
}

const args = parseArgs(process.argv.slice(2));
if (args.prompt && args.output) {
  generateImage(args);
} else if (process.argv.length > 2) {
  console.error('Usage: node banatie.mjs --type <background|icon> --prompt "<description>" --output <path>');
  process.exit(1);
}
