/**
 * Production readiness static checks for Tryonixs WooCommerce plugin.
 * Run: node scripts/production-check.js
 */
const fs = require('fs');
const path = require('path');

const root = path.resolve(__dirname, '..');
const errors = [];
const warnings = [];
const passes = [];

function ok(msg) { passes.push(msg); }
function fail(msg) { errors.push(msg); }
function warn(msg) { warnings.push(msg); }

function read(rel) {
  return fs.readFileSync(path.join(root, rel), 'utf8');
}

function exists(rel) {
  return fs.existsSync(path.join(root, rel));
}

// --- Required files ---
const required = [
  'tryonixs-virtual-try-on-for-eyewear-stores.php',
  'readme.txt',
  'includes/helpers.php',
  'includes/frontend.php',
  'includes/admin.php',
  'includes/product-meta.php',
  'includes/onboarding.php',
  'assets/tryonixs.js',
  'assets/tryonixs.css',
  'assets/admin/admin.js',
  'assets/admin/admin.css',
];

required.forEach((f) => (exists(f) ? ok(`File exists: ${f}`) : fail(`Missing file: ${f}`)));

// --- Version sync ---
const main = read('tryonixs-virtual-try-on-for-eyewear-stores.php');
const readme = read('readme.txt');
const headerVersion = (main.match(/\*\s*Version:\s*([0-9.]+)/) || [])[1];
const defineVersion = (main.match(/define\('EYEWVITR_VERSION',\s*'([^']+)'\)/) || [])[1];
const stableTag = (readme.match(/Stable tag:\s*([0-9.]+)/) || [])[1];
const testedUpTo = (readme.match(/Tested up to:\s*([0-9.]+)/) || [])[1];

if (headerVersion && defineVersion && stableTag && headerVersion === defineVersion && defineVersion === stableTag) {
  ok(`Version synced: ${headerVersion}`);
} else {
  fail(`Version mismatch header=${headerVersion} define=${defineVersion} stable=${stableTag}`);
}

if (stableTag === '1.3.7') ok('Stable tag is 1.3.7');
else fail(`Expected Stable tag 1.3.7, got ${stableTag}`);

if (testedUpTo === '7.0') ok('Tested up to is 7.0');
else fail(`Expected Tested up to 7.0, got ${testedUpTo}`);

const pluginUri = (main.match(/\*\s*Plugin URI:\s*(\S+)/) || [])[1] || '';
const authorUri = (main.match(/\*\s*Author URI:\s*(\S+)/) || [])[1] || '';
if (pluginUri && authorUri && pluginUri === authorUri) {
  fail(`Plugin URI and Author URI must differ: ${pluginUri}`);
} else if (pluginUri && authorUri) {
  ok(`Plugin URI (${pluginUri}) differs from Author URI (${authorUri})`);
} else {
  ok('Only one of Plugin URI / Author URI is set (allowed)');
}

// Display name must not include restricted trademark terms.
const pluginNameLine = (main.match(/\*\s*Plugin Name:\s*(.+)/) || [])[1] || '';
const readmeTitle = (readme.match(/^===\s*(.+?)\s*===/) || [])[1] || '';
if (/woocommerce/i.test(pluginNameLine) || /woocommerce/i.test(readmeTitle)) {
  fail(`Display name contains restricted term "woocommerce": plugin="${pluginNameLine}" readme="${readmeTitle}"`);
} else {
  ok(`Display name trademark-safe: ${pluginNameLine.trim()}`);
}

// --- Plugin header ---
[
  ['Plugin Name:', 'Tryonixs Virtual Try-On for Eyewear Stores'],
  ['Plugin URI:', 'https://tryonixs.com'],
  ['Author:', 'Tryonixs'],
  ['Author URI:', 'https://tryonixs.com'],
  ['License:', 'GPLv2'],
].forEach(([key, expected]) => {
  if (main.includes(key) && main.includes(expected)) ok(`Header has ${key} ${expected}`);
  else fail(`Header missing or wrong: ${key} / ${expected}`);
});

const textDomain = (main.match(/\*\s*Text Domain:\s*(\S+)/) || [])[1];
const slug = 'tryonixs-virtual-try-on-for-eyewear-stores';
if (textDomain === slug) ok(`Text Domain matches slug: ${textDomain}`);
else fail(`Text Domain mismatch: ${textDomain} vs slug ${slug}`);

// --- readme tags ---
const tagsLine = (readme.match(/Tags:\s*(.+)/) || [])[1] || '';
const tags = tagsLine.split(',').map((t) => t.trim()).filter(Boolean);
if (tags.length === 5) ok(`Exactly 5 tags: ${tags.join(', ')}`);
else fail(`Expected 5 tags, found ${tags.length}: ${tagsLine}`);
if (tags.includes('tryonixs')) fail('Brand tag tryonixs should not be in discovery tags');
else ok('No brand-only tryonixs tag');

if (/not affiliated/i.test(readme)) fail('readme still contains "not affiliated" disclaimer');
else ok('Bad affiliation disclaimer removed from readme');

// --- i18n domain literals ---
const phpFiles = required.filter((f) => f.endsWith('.php'));
let i18nIssues = 0;
phpFiles.forEach((f) => {
  const src = read(f);
  const badConst = src.match(/__\([^)]*EYEWVITR_|esc_html[^\n]*EYEWVITR_/g);
  if (badConst) {
    i18nIssues += badConst.length;
    fail(`${f}: translation domain uses constant`);
  }
  // domains that aren't the literal slug string
  const calls = src.matchAll(/(?:__|_e|esc_html__|esc_html_e|esc_attr__|esc_attr_e|_x|_n)\(\s*(?:[^,]+,)\s*([^)\n]+)/g);
  for (const m of calls) {
    const domain = m[1].trim();
    if (domain.includes('TEXT_DOMAIN') || domain.startsWith('$')) {
      i18nIssues += 1;
      fail(`${f}: non-literal domain ${domain}`);
    }
  }
});
if (i18nIssues === 0) ok('All i18n domains appear as string literals');

// --- Prefixing ---
const allPhp = phpFiles.map(read).join('\n');
const fnDefs = [...allPhp.matchAll(/function\s+([a-zA-Z0-9_]+)\s*\(/g)].map((m) => m[1]);
const badFns = fnDefs.filter((n) => !n.startsWith('eyewvitr_'));
if (badFns.length === 0) ok(`All ${fnDefs.length} functions use eyewvitr_ prefix`);
else fail(`Unprefixed functions: ${badFns.join(', ')}`);

if (/add_shortcode\(\s*'eyewvitr_button'/.test(allPhp)) ok('Shortcode eyewvitr_button registered');
else fail('Shortcode eyewvitr_button missing');

if (/define\(\s*'EYEWVITR_/.test(allPhp)) ok('Defines use EYEWVITR_ prefix');
else fail('Missing EYEWVITR_ defines');

// --- Security ---
if (/check_ajax_referer\(\s*'eyewvitr_frontend'/.test(allPhp)) ok('AJAX nonce verification present');
else fail('Missing AJAX nonce check');

if (/wp_verify_nonce/.test(allPhp) && /woocommerce_meta_nonce/.test(allPhp)) ok('Product meta nonce verification present');
else fail('Missing product meta nonce verification');

if (/sanitize_text_field|esc_url_raw|sanitize_callback/.test(allPhp)) ok('Input sanitization present');
else fail('Sanitization missing');

if (/esc_html|esc_attr|esc_url/.test(allPhp)) ok('Output escaping present');
else fail('Output escaping missing');

// --- Frontend productId ---
const js = read('assets/tryonixs.js');
if (/productId:\s*String\(productId\)/.test(js)) ok('JS always passes productId: String(productId)');
else fail('JS productId not required in Tryonixs.open options');

if (/Tryonixs\.open\(openOptions\)/.test(js)) ok('Tryonixs.open called with openOptions');
else fail('Tryonixs.open call missing');

if (/if\s*\(!productId\)/.test(js)) ok('JS validates missing productId');
else fail('JS missing productId validation');

if (/data-product-id="%2\$s"/.test(allPhp) || /data-product-id="%2\$s"/.test(read('includes/frontend.php'))) {
  ok('Button renders data-product-id');
} else {
  fail('Button missing data-product-id attribute');
}

// --- Architecture requires ---
['helpers.php', 'frontend.php', 'product-meta.php', 'admin.php', 'onboarding.php'].forEach((f) => {
  if (main.includes(`includes/${f}`)) ok(`Bootstrap loads includes/${f}`);
  else fail(`Bootstrap missing require for includes/${f}`);
});

// --- Asset refs ---
['assets/tryonixs.css', 'assets/tryonixs.js', 'assets/admin/admin.css', 'assets/admin/admin.js'].forEach((f) => {
  if (allPhp.includes(f)) ok(`PHP enqueues/references ${f}`);
  else fail(`PHP does not reference ${f}`);
});

// --- Feature checklist ---
if (/eyewvitr_settings_page|Welcome to Tryonixs Virtual Try-On/.test(allPhp)) ok('SaaS dashboard present');
else fail('Dashboard missing');

if (/eyewvitr_welcome_page|Welcome to Tryonixs/.test(allPhp)) ok('Onboarding welcome page present');
else fail('Onboarding missing');

if (/eyewvitr_review_notice|_frame_width|_lens_height|_temple_length/.test(allPhp)) ok('Review system + frame fields present');
else fail('Review system or frame fields missing');

if (/register_activation_hook/.test(main)) ok('Activation hook registered in main file');
else fail('Activation hook missing from main file');

// --- Folder slug hint ---
const folder = path.basename(root);
if (folder !== slug) {
  warn(`Workspace folder "${folder}" differs from plugin slug "${slug}". ZIP folder for WP.org should be named "${slug}".`);
} else {
  ok('Folder name matches plugin slug');
}

// --- WP.org assets (optional for runtime, required for directory listing) ---
const assetFiles = [
  'wporg-assets/icon-256x256.png',
  'wporg-assets/icon-512x512.png',
  'wporg-assets/banner-772x250.png',
  'wporg-assets/screenshot-1.png',
  'wporg-assets/screenshot-2.png',
  'wporg-assets/screenshot-3.png',
  'wporg-assets/screenshot-4.png',
  'wporg-assets/screenshot-5.png',
];
assetFiles.forEach((f) => (exists(f) ? ok(`WP.org asset ready: ${f}`) : warn(`Missing WP.org asset: ${f}`)));

// Report
console.log('\n=== PRODUCTION READINESS REPORT ===\n');
passes.forEach((m) => console.log('PASS  ' + m));
warnings.forEach((m) => console.log('WARN  ' + m));
errors.forEach((m) => console.log('FAIL  ' + m));
console.log(`\nSummary: ${passes.length} passed, ${warnings.length} warnings, ${errors.length} failures\n`);

if (errors.length) {
  process.exit(1);
}
console.log('RESULT: READY FOR PRODUCTION (code checks)\n');
console.log('Reminder: create SVN tag /tags/1.3.4/ after upload, or Stable Tag will fail on WordPress.org.');
