#!/usr/bin/env node

/**
 * Script to inject the FurryPlace SDK into the frontend HTML files
 *
 * This modifies the HTML files to include the SDK script tag
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const FRONTEND_DIR = path.join(__dirname, '..', 'frontend-backup');
const SDK_PATH = '/furryplace-sdk.js';
const HTML_FILES = ['index.html', 'admin.html', 'moderation.html'];

function injectSDK(htmlPath) {
  console.log(`Processing ${htmlPath}...`);

  let content = fs.readFileSync(htmlPath, 'utf8');

  // Check if SDK is already injected
  if (content.includes('furryplace-sdk.js')) {
    console.log(`  ✓ SDK already injected in ${path.basename(htmlPath)}`);
    return;
  }

  // Find the closing </head> tag and inject before it
  const headCloseTag = '</head>';
  const headCloseIndex = content.indexOf(headCloseTag);

  if (headCloseIndex === -1) {
    console.error(`  ✗ Could not find </head> tag in ${path.basename(htmlPath)}`);
    return;
  }

  // Create the SDK script tag
  const sdkScript = `\n\t\t<!-- FurryPlace SDK for custom button extensions -->\n\t\t<script src="${SDK_PATH}"></script>\n\t`;

  // Inject the script
  content = content.slice(0, headCloseIndex) + sdkScript + content.slice(headCloseIndex);

  // Write back
  fs.writeFileSync(htmlPath, content, 'utf8');
  console.log(`  ✓ SDK injected into ${path.basename(htmlPath)}`);
}

function main() {
  console.log('FurryPlace SDK Injection Script\n');

  // Check if SDK file exists
  const sdkFilePath = path.join(FRONTEND_DIR, 'furryplace-sdk.js');
  if (!fs.existsSync(sdkFilePath)) {
    console.error(`Error: SDK file not found at ${sdkFilePath}`);
    process.exit(1);
  }

  console.log(`SDK file found: ${sdkFilePath}\n`);

  // Process each HTML file
  HTML_FILES.forEach(file => {
    const htmlPath = path.join(FRONTEND_DIR, file);

    if (!fs.existsSync(htmlPath)) {
      console.warn(`Warning: ${file} not found, skipping...`);
      return;
    }

    injectSDK(htmlPath);
  });

  console.log('\n✓ SDK injection complete!');
  console.log('\nYou can now create plugins by adding a script tag to your HTML:');
  console.log('  <script src="/plugins/my-plugin.js"></script>');
}

main();
