#!/usr/bin/env node
/**
 * Generate Documentation with Mock UI for SmartStack Modules
 *
 * This script generates complete documentation pages with embedded mock UI components
 * that visually represent the module's interface without requiring real screenshots.
 *
 * Usage:
 *   node generate-doc-with-mock-ui.ts \
 *     --module users \
 *     --application administration \
 *     --app-path "D:/01 - projets/SmartStack.app/02-Develop"
 *
 * Output: Complete TSX file with mock UI (e.g., UsersDocPage.tsx)
 */

import * as fs from 'fs';
import * as path from 'path';
import { glob } from 'glob';
import { execSync } from 'child_process';

interface ModuleInfo {
  module: string;        // e.g., "users"
  application: string;   // e.g., "administration"
  appPath: string;
}

interface EntityProperty {
  name: string;          // e.g., "Email", "FirstName"
  type: string;          // e.g., "string", "bool", "DateTime?"
  isRequired: boolean;
  isNullable: boolean;
}

interface MockDataField {
  propertyName: string;
  mockValue: string;     // Generated mock value
}

interface PageStructure {
  hasTable: boolean;
  hasKPIs: boolean;
  hasForm: boolean;
  hasFilters: boolean;
  columns: string[];     // Table column names
}

/**
 * Parse command line arguments
 */
function parseArgs(): ModuleInfo {
  const args = process.argv.slice(2);

  const getArg = (flag: string): string | null => {
    const index = args.indexOf(flag);
    return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
  };

  const module = getArg('--module');
  const application = getArg('--application');
  const appPath = getArg('--app-path');

  if (!module || !application || !appPath) {
    console.error('Usage: node generate-doc-with-mock-ui.ts --module <name> --application <app> --app-path <path>');
    process.exit(1);
  }

  return { module, application, appPath };
}

/**
 * Find Domain entity file
 * Tries both singular and plural forms (e.g., users → User.cs)
 */
async function findEntityFile(appPath: string, module: string): Promise<string | null> {
  const domainPath = path.join(appPath, 'src/SmartStack.Domain');

  // Try singular form first (most common: users → User.cs)
  const singularForm = capitalize(singularize(module));
  const singularPattern = `**/${singularForm}.cs`;

  try {
    let files = await glob(singularPattern, { cwd: domainPath, absolute: true });
    if (files.length > 0) {
      return files[0];
    }

    // Fallback to plural form
    const pluralForm = capitalize(module);
    const pluralPattern = `**/${pluralForm}.cs`;
    files = await glob(pluralPattern, { cwd: domainPath, absolute: true });
    return files.length > 0 ? files[0] : null;
  } catch (error) {
    console.error('Error finding entity:', error);
    return null;
  }
}

/**
 * Find React page file
 */
async function findPageFile(appPath: string, module: string, application: string): Promise<string | null> {
  const pagesPath = path.join(appPath, `web/smartstack-web/src/pages/${application}/${module}`);
  const pattern = `${capitalize(module)}Page.tsx`;

  const fullPath = path.join(pagesPath, pattern);
  return fs.existsSync(fullPath) ? fullPath : null;
}

/**
 * Extract entity properties from Domain entity file
 */
function extractEntityProperties(entityPath: string): EntityProperty[] {
  const content = fs.readFileSync(entityPath, 'utf-8');
  const lines = content.split('\n');
  const properties: EntityProperty[] = [];

  for (const line of lines) {
    // Match property declarations: public string Email { get; private set; }
    const propMatch = line.match(/public\s+(\w+\??)\s+(\w+)\s*\{\s*get;/);
    if (propMatch) {
      const type = propMatch[1];
      const name = propMatch[2];

      // Skip base entity properties and navigation properties
      if (['Id', 'CreatedAt', 'UpdatedAt', 'CreatedBy', 'UpdatedBy'].includes(name)) {
        continue;
      }

      // Skip collections (List, IReadOnlyCollection, etc.)
      if (line.includes('List<') || line.includes('IReadOnlyCollection<') || line.includes('ICollection<')) {
        continue;
      }

      properties.push({
        name,
        type,
        isRequired: !type.endsWith('?'),
        isNullable: type.endsWith('?'),
      });
    }
  }

  return properties;
}

/**
 * Analyze React page structure
 */
function analyzePageStructure(pagePath: string): PageStructure {
  const content = fs.readFileSync(pagePath, 'utf-8');

  const structure: PageStructure = {
    hasTable: content.includes('<table') || content.includes('Table'),
    hasKPIs: content.includes('KPI') || content.includes('stat') || content.includes('metric'),
    hasForm: content.includes('<form') || content.includes('Form') || content.includes('input'),
    hasFilters: content.includes('filter') || content.includes('Filter') || content.includes('search'),
    columns: [],
  };

  // Try to extract table column names
  const thRegex = /<th[^>]*>([^<]+)<\/th>/g;
  let match;
  while ((match = thRegex.exec(content)) !== null) {
    structure.columns.push(match[1].trim());
  }

  return structure;
}

/**
 * Generate mock value for a property
 */
function generateMockValue(property: EntityProperty, index: number): string {
  const type = property.type.replace('?', '');

  switch (type.toLowerCase()) {
    case 'string':
      if (property.name.toLowerCase().includes('email')) {
        const names = ['john.doe', 'jane.smith', 'bob.johnson', 'alice.williams', 'charlie.brown'];
        return `"${names[index % names.length]}@example.com"`;
      }
      if (property.name.toLowerCase().includes('name')) {
        if (property.name.toLowerCase().includes('first')) {
          const names = ['John', 'Jane', 'Bob', 'Alice', 'Charlie'];
          return `"${names[index % names.length]}"`;
        }
        if (property.name.toLowerCase().includes('last')) {
          const names = ['Doe', 'Smith', 'Johnson', 'Williams', 'Brown'];
          return `"${names[index % names.length]}"`;
        }
        return `"${property.name} ${index + 1}"`;
      }
      if (property.name.toLowerCase().includes('title')) {
        return `"Sample ${property.name} ${index + 1}"`;
      }
      if (property.name.toLowerCase().includes('description')) {
        return `"This is a sample description for item ${index + 1}"`;
      }
      return `"Sample ${property.name}"`;

    case 'bool':
    case 'boolean':
      return index % 2 === 0 ? 'true' : 'false';

    case 'int':
    case 'int32':
    case 'long':
      return String((index + 1) * 10);

    case 'decimal':
    case 'double':
    case 'float':
      return String((index + 1) * 10.5);

    case 'datetime':
      const dates = ['2026-01-15', '2026-01-20', '2026-02-01', '2026-02-10', '2026-02-15'];
      return `"${dates[index % dates.length]}"`;

    case 'guid':
      // Generate a fixed mock GUID based on index to keep consistent data
      const mockGuids = [
        '"550e8400-e29b-41d4-a716-446655440000"',
        '"6ba7b810-9dad-11d1-80b4-00c04fd430c8"',
        '"6ba7b811-9dad-11d1-80b4-00c04fd430c9"',
        '"6ba7b812-9dad-11d1-80b4-00c04fd430ca"',
        '"6ba7b813-9dad-11d1-80b4-00c04fd430cb"'
      ];
      return mockGuids[index % mockGuids.length];

    default:
      return property.isNullable ? 'null' : '""';
  }
}

/**
 * Generate mock data array
 */
function generateMockData(properties: EntityProperty[], module: string, count: number = 5): string {
  const mockItems: string[] = [];

  for (let i = 0; i < count; i++) {
    const fields = properties
      .filter(p => !p.name.includes('Hash') && !p.name.includes('Token')) // Skip sensitive fields
      .map(p => `${p.name.charAt(0).toLowerCase() + p.name.slice(1)}: ${generateMockValue(p, i)}`)
      .join(', ');

    mockItems.push(`  { ${fields} }`);
  }

  const singularName = module.endsWith('s') ? module.slice(0, -1) : module;
  return `const mock${capitalize(module)} = [\n${mockItems.join(',\n')}\n];`;
}

/**
 * Generate KPI stats based on entity properties
 */
function generateKPIStats(properties: EntityProperty[], module: string, count: number = 5): string {
  const stats: string[] = [];

  // Always add total count
  stats.push(`  { label: 'Total', value: '${count * 10}', color: 'var(--text-primary)' }`);

  // Check for IsActive/Status property
  const activeProperty = properties.find(p =>
    p.name.toLowerCase() === 'isactive' && (p.type.toLowerCase() === 'bool' || p.type.toLowerCase() === 'boolean')
  );

  if (activeProperty) {
    const activeCount = Math.floor(count * 10 * 0.6); // 60% active
    const inactiveCount = count * 10 - activeCount;
    stats.push(`  { label: 'Active', value: '${activeCount}', color: 'var(--success-text)', border: 'var(--success-border)' }`);
    stats.push(`  { label: 'Inactive', value: '${inactiveCount}', color: 'var(--error-text)', border: 'var(--error-border)' }`);
  }

  // Check for Status property (enum/string)
  const statusProperty = properties.find(p =>
    p.name.toLowerCase() === 'status' && p.type.toLowerCase() === 'string'
  );

  if (statusProperty) {
    stats.push(`  { label: 'Pending', value: '${Math.floor(count * 2)}', color: 'var(--warning-text)', border: 'var(--warning-border)' }`);
    stats.push(`  { label: 'In Progress', value: '${Math.floor(count * 3)}', color: 'var(--info-text)', border: 'var(--info-border)' }`);
    stats.push(`  { label: 'Completed', value: '${Math.floor(count * 5)}', color: 'var(--success-text)', border: 'var(--success-border)' }`);
  }

  // Check for DateTime property (e.g., CreatedAt, LastLoginAt)
  const dateProperty = properties.find(p =>
    p.type.toLowerCase() === 'datetime' &&
    (p.name.toLowerCase().includes('created') || p.name.toLowerCase().includes('login'))
  );

  if (dateProperty) {
    stats.push(`  { label: 'Last 7 days', value: '${Math.floor(count * 1.5)}', color: 'var(--info-text)', border: 'var(--info-border)' }`);
  }

  return `const ${module}Stats = [\n${stats.join(',\n')}\n];`;
}

/**
 * Generate form fields based on entity properties
 */
function generateFormSection(properties: EntityProperty[], module: string): string {
  const ModuleName = capitalize(singularize(module));

  // Filter properties suitable for form input
  const formProps = properties.filter(p => {
    const name = p.name.toLowerCase();
    // Exclude read-only, computed, and sensitive fields
    return !name.includes('hash') &&
           !name.includes('token') &&
           !name.includes('normalized') &&
           !name.endsWith('id') &&
           !name.includes('createdat') &&
           !name.includes('updatedat') &&
           !name.includes('createdby') &&
           !name.includes('updatedby') &&
           !name.includes('data') &&
           !name.includes('proxy') &&
           p.name !== 'Id';
  }).slice(0, 6); // Limit to 6 most relevant fields

  const formFields = formProps.map(p => {
    const fieldName = p.name.charAt(0).toLowerCase() + p.name.slice(1);
    const label = p.name.replace(/([A-Z])/g, ' $1').trim();
    const isRequired = p.isRequired;

    if (p.type.toLowerCase() === 'bool' || p.type.toLowerCase() === 'boolean') {
      return `            <div className="flex items-center gap-2">
              <input type="checkbox" id="${fieldName}" className="w-4 h-4" />
              <label htmlFor="${fieldName}" className="text-sm">${label}</label>
            </div>`;
    }

    if (p.type.toLowerCase() === 'datetime') {
      return `            <div>
              <label className="block text-sm font-medium mb-1">${label}${isRequired ? ' *' : ''}</label>
              <input type="date" className="w-full px-3 py-2 border border-[var(--border-color)] rounded-lg" />
            </div>`;
    }

    if (p.name.toLowerCase().includes('email')) {
      return `            <div>
              <label className="block text-sm font-medium mb-1">${label}${isRequired ? ' *' : ''}</label>
              <input type="email" placeholder="user@example.com" className="w-full px-3 py-2 border border-[var(--border-color)] rounded-lg" />
            </div>`;
    }

    if (p.name.toLowerCase().includes('description') || p.name.toLowerCase().includes('notes')) {
      return `            <div className="md:col-span-2">
              <label className="block text-sm font-medium mb-1">${label}</label>
              <textarea rows={3} className="w-full px-3 py-2 border border-[var(--border-color)] rounded-lg" />
            </div>`;
    }

    // Default text input
    return `            <div>
              <label className="block text-sm font-medium mb-1">${label}${isRequired ? ' *' : ''}</label>
              <input type="text" className="w-full px-3 py-2 border border-[var(--border-color)] rounded-lg" />
            </div>`;
  }).join('\n');

  return `      {/* Section 4: Create Form Example */}
      <section id="create-form" className="card p-6">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <span className="w-8 h-8 rounded-full bg-[var(--color-primary-600)] text-white flex items-center justify-center text-sm font-bold">4</span>
          Create ${ModuleName} Form
        </h2>
        <p className="text-[var(--text-secondary)] mb-4">
          Form interface for creating new ${module}.
        </p>

        <div className="border border-[var(--border-color)] rounded-lg p-6 bg-[var(--bg-secondary)]">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
${formFields}
          </div>

          <div className="flex items-center gap-3 mt-6 pt-6 border-t border-[var(--border-color)]">
            <button className="px-4 py-2 bg-[var(--color-primary-600)] text-white rounded-lg flex items-center gap-2">
              <Plus className="w-4 h-4" />
              Create ${ModuleName}
            </button>
            <button className="px-4 py-2 border border-[var(--border-color)] rounded-lg">
              Cancel
            </button>
          </div>
        </div>
      </section>`;
}

/**
 * Generate KPI section UI
 */
function generateKPISection(module: string): string {
  return `          {/* Stats */}
          <div className="p-4 border-b border-[var(--border-color)] bg-[var(--bg-secondary)]">
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2">
              {${module}Stats.map((stat) => (
                <div
                  key={stat.label}
                  className="p-3 bg-[var(--bg-primary)] rounded-lg text-center"
                  style={{ borderLeft: stat.border ? \`3px solid \${stat.border}\` : undefined }}
                >
                  <div className="text-2xl font-bold" style={{ color: stat.color }}>{stat.value}</div>
                  <div className="text-xs text-[var(--text-secondary)] mt-1">{stat.label}</div>
                </div>
              ))}
            </div>
          </div>`;
}

/**
 * Generate table mock UI section
 */
function generateTableMockUI(properties: EntityProperty[], module: string): string {
  // Smart property selection for table display
  const filteredProps = properties.filter(p => {
    const name = p.name.toLowerCase();
    // Exclude sensitive, internal, and FK properties
    return !name.includes('hash') &&
           !name.includes('token') &&
           !name.includes('password') &&
           !name.endsWith('id') &&  // Skip foreign keys
           !name.includes('normalized') &&
           !name.includes('data') &&  // Skip JSON/blob fields
           !name.includes('proxy') &&
           !name.includes('im') &&
           p.name !== 'Sponsors' &&
           p.name !== 'ProxyAddresses' &&
           p.name !== 'ImAddresses';
  });

  // Prioritize display properties: name/title > email > status > date
  const priorityProps: EntityProperty[] = [];

  // Add name/title properties first
  priorityProps.push(...filteredProps.filter(p =>
    p.name.toLowerCase().includes('name') ||
    p.name.toLowerCase().includes('title')
  ).slice(0, 2));

  // Add email if available
  const emailProp = filteredProps.find(p => p.name.toLowerCase().includes('email'));
  if (emailProp && !priorityProps.includes(emailProp)) {
    priorityProps.push(emailProp);
  }

  // Add status/active properties
  const statusProp = filteredProps.find(p =>
    p.name.toLowerCase().includes('active') ||
    p.name.toLowerCase().includes('status')
  );
  if (statusProp && !priorityProps.includes(statusProp)) {
    priorityProps.push(statusProp);
  }

  // Fill remaining slots with other properties (max 6 total)
  const remainingProps = filteredProps.filter(p => !priorityProps.includes(p));
  priorityProps.push(...remainingProps.slice(0, 6 - priorityProps.length));

  const displayProps = priorityProps.slice(0, 6);

  const headers = displayProps.map(p => `<th className="text-left p-3 font-medium">${p.name}</th>`).join('\n                  ');

  const cells = displayProps.map(p => {
    const propName = p.name.charAt(0).toLowerCase() + p.name.slice(1);

    if (p.type.toLowerCase() === 'bool' || p.type.toLowerCase() === 'boolean') {
      return `<td className="p-3">
                      <span className={\`px-2 py-1 text-xs rounded \${item.${propName} ? 'bg-green-500/10 text-green-600' : 'bg-gray-500/10 text-gray-600'}\`}>
                        {item.${propName} ? 'Yes' : 'No'}
                      </span>
                    </td>`;
    }

    if (p.type.toLowerCase() === 'datetime') {
      return `<td className="p-3 text-[var(--text-secondary)]">{new Date(item.${propName}).toLocaleDateString()}</td>`;
    }

    return `<td className="p-3">{item.${propName}}</td>`;
  }).join('\n                    ');

  return `        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-[var(--bg-secondary)]">
              <tr>
                ${headers}
                <th className="text-right p-3 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {mock${capitalize(module)}.map((item, idx) => (
                <tr key={idx} className="border-b border-[var(--border-color)] hover:bg-[var(--bg-hover)]">
                  ${cells}
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <button className="p-1.5 hover:bg-[var(--bg-secondary)] rounded">
                        <Eye className="w-4 h-4" />
                      </button>
                      <button className="p-1.5 hover:bg-[var(--bg-secondary)] rounded text-[var(--error-text)]">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>`;
}

/**
 * Generate complete TSX documentation file
 */
function generateDocumentationTSX(
  moduleInfo: ModuleInfo,
  properties: EntityProperty[],
  apiEndpoints: any[],
  businessRules: any[],
  pageStructure: PageStructure
): string {
  const { module, application } = moduleInfo;
  const ModuleName = capitalize(module);

  // Generate mock data
  const mockDataCode = generateMockData(properties, module);

  // Generate KPI stats
  const kpiStatsCode = generateKPIStats(properties, module);
  const kpiSectionUI = generateKPISection(module);

  // Generate table UI
  const tableMockUI = generateTableMockUI(properties, module);

  // Generate form section
  const formSectionUI = generateFormSection(properties, module);

  // Generate API endpoints mock data
  const apiEndpointsCode = `const apiEndpoints = ${JSON.stringify(apiEndpoints, null, 2)};`;

  return `import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  ArrowRight,
  Shield,
  Eye,
  Trash2,
  Plus,
  Info,
  MessageSquare,
  HelpCircle,
} from 'lucide-react';

// Mock data for ${ModuleName}
${mockDataCode}

// KPI Stats
${kpiStatsCode}

// API endpoints
${apiEndpointsCode}

export function ${ModuleName}DocPage() {
  const { t } = useTranslation('docs');

  return (
    <div className="space-y-8">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)]">
        <Link to="/system/docs" className="hover:text-[var(--color-primary-600)]">Documentation</Link>
        <span>/</span>
        <Link to="/system/docs/user" className="hover:text-[var(--color-primary-600)]">User</Link>
        <span>/</span>
        <span>${ModuleName}</span>
      </div>

      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold mb-4">
          ${ModuleName} Management
        </h1>
        <p className="text-lg text-[var(--text-secondary)]">
          Complete management interface for ${module}
        </p>
      </div>

      {/* Section 1: Introduction */}
      <section id="introduction" className="card p-6">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <span className="w-8 h-8 rounded-full bg-[var(--color-primary-600)] text-white flex items-center justify-center text-sm font-bold">1</span>
          Introduction
        </h2>
        <p className="text-[var(--text-secondary)]">
          The ${ModuleName} module provides comprehensive management capabilities including
          viewing, creating, updating, and deleting ${module}.
        </p>
      </section>

      {/* Section 2: Access */}
      <section id="access" className="card p-6">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <span className="w-8 h-8 rounded-full bg-[var(--color-primary-600)] text-white flex items-center justify-center text-sm font-bold">2</span>
          Access
        </h2>

        <div className="mb-4">
          <div className="text-sm font-medium mb-2">Navigation</div>
          <div className="flex items-center gap-2 text-sm bg-[var(--bg-secondary)] p-3 rounded-lg">
            <span className="px-2 py-1 bg-[var(--bg-primary)] rounded">${capitalize(application)}</span>
            <ArrowRight className="w-4 h-4 text-[var(--text-tertiary)]" />
            <span className="px-2 py-1 bg-[var(--color-primary-600)] text-white rounded">${ModuleName}</span>
          </div>
        </div>

        <div className="mb-4">
          <div className="text-sm font-medium mb-2">URL</div>
          <code className="block p-3 bg-[var(--bg-secondary)] rounded-lg text-sm font-mono">
            /${application}/${module}
          </code>
        </div>
      </section>

      {/* Section 3: Overview - MOCK UI */}
      <section id="overview" className="card p-6">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <span className="w-8 h-8 rounded-full bg-[var(--color-primary-600)] text-white flex items-center justify-center text-sm font-bold">3</span>
          Interface Overview
        </h2>
        <p className="text-[var(--text-secondary)] mb-4">
          The main ${module} interface displays all records in a table format with search and filter capabilities.
        </p>

        {/* Mock UI - Complete Interface */}
        <div className="border border-[var(--border-color)] rounded-lg overflow-hidden">
          {/* Header */}
          <div className="p-4 border-b border-[var(--border-color)] flex items-center justify-between">
            <div>
              <div className="font-bold">${ModuleName} Management</div>
              <div className="text-sm text-[var(--text-secondary)]">Manage all ${module}</div>
            </div>
            <button className="px-4 py-2 bg-[var(--color-primary-600)] text-white rounded-lg flex items-center gap-2 text-sm">
              <Plus className="w-4 h-4" />
              New ${ModuleName}
            </button>
          </div>

${kpiSectionUI}

          {/* Table */}
${tableMockUI}
        </div>
      </section>

${formSectionUI}

      {/* Section 5: API Reference */}
      <section id="api" className="card p-6">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <span className="w-8 h-8 rounded-full bg-[var(--color-primary-600)] text-white flex items-center justify-center text-sm font-bold">5</span>
          API Reference
        </h2>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-[var(--bg-secondary)]">
                <th className="text-left py-2 px-3 rounded-tl-lg">Method</th>
                <th className="text-left py-2 px-3">Endpoint</th>
                <th className="text-left py-2 px-3 rounded-tr-lg">Handler</th>
              </tr>
            </thead>
            <tbody>
              {apiEndpoints.map((endpoint, index) => (
                <tr key={index} className="border-b border-[var(--border-color)]">
                  <td className="py-2 px-3">
                    <span className={\`px-2 py-0.5 rounded text-xs font-medium \${
                      endpoint.method === 'GET' ? 'bg-green-500/10 text-green-600' :
                      endpoint.method === 'POST' ? 'bg-yellow-500/10 text-yellow-600' :
                      endpoint.method === 'PUT' ? 'bg-blue-500/10 text-blue-600' :
                      'bg-red-500/10 text-red-600'
                    }\`}>
                      {endpoint.method}
                    </span>
                  </td>
                  <td className="py-2 px-3 font-mono text-xs">{endpoint.path}</td>
                  <td className="py-2 px-3 text-[var(--text-secondary)]">{endpoint.handler}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
`;
}

/**
 * Capitalize first letter
 */
function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * Simple singularize function for common English plurals
 */
function singularize(str: string): string {
  if (str.endsWith('ies')) {
    return str.slice(0, -3) + 'y';
  }
  if (str.endsWith('sses') || str.endsWith('shes') || str.endsWith('ches') || str.endsWith('xes')) {
    return str.slice(0, -2);
  }
  if (str.endsWith('s') && !str.endsWith('ss')) {
    return str.slice(0, -1);
  }
  return str;
}

/**
 * Main execution
 */
async function main() {
  const moduleInfo = parseArgs();
  const { module, application, appPath } = moduleInfo;

  console.error(`\n🚀 Generating documentation for: ${application}/${module}\n`);

  // 1. Find entity file
  console.error('📁 Finding entity file...');
  const entityPath = await findEntityFile(appPath, module);
  if (!entityPath) {
    console.error(`❌ Entity not found for module: ${module}`);
    process.exit(1);
  }
  console.error(`✅ Found: ${entityPath}`);

  // 2. Extract entity properties
  console.error('\n📊 Extracting entity properties...');
  const properties = extractEntityProperties(entityPath);
  console.error(`✅ Extracted ${properties.length} properties`);

  // 3. Find page file
  console.error('\n📄 Finding React page...');
  const pagePath = await findPageFile(appPath, module, application);
  if (pagePath) {
    console.error(`✅ Found: ${pagePath}`);
  } else {
    console.error(`⚠️  Page not found (will use defaults)`);
  }

  // 4. Analyze page structure
  const pageStructure = pagePath ? analyzePageStructure(pagePath) : {
    hasTable: true,
    hasKPIs: false,
    hasForm: false,
    hasFilters: false,
    columns: [],
  };

  // 5. Extract API endpoints using existing script
  console.error('\n🔌 Extracting API endpoints...');
  let apiEndpoints: any[] = [];
  try {
    const endpointsOutput = execSync(
      `npx tsx "${__dirname}/extract-api-endpoints.ts" --module ${module} --app-path "${appPath}"`,
      { encoding: 'utf-8' }
    );
    apiEndpoints = JSON.parse(endpointsOutput);
    console.error(`✅ Extracted ${apiEndpoints.length} endpoints`);
  } catch (error) {
    console.error(`⚠️  Could not extract endpoints`);
  }

  // 6. Extract business rules using existing script
  console.error('\n📋 Extracting business rules...');
  let businessRules: any[] = [];
  try {
    const rulesOutput = execSync(
      `npx tsx "${__dirname}/extract-business-rules.ts" --module ${module} --app-path "${appPath}"`,
      { encoding: 'utf-8' }
    );
    businessRules = JSON.parse(rulesOutput);
    console.error(`✅ Extracted ${businessRules.length} business rules`);
  } catch (error) {
    console.error(`⚠️  Could not extract business rules`);
  }

  // 7. Generate documentation TSX
  console.error('\n✨ Generating documentation TSX...');
  const tsx = generateDocumentationTSX(moduleInfo, properties, apiEndpoints, businessRules, pageStructure);

  // 8. Output
  console.log(tsx);
  console.error('\n✅ Documentation generated successfully!');
}

main().catch((error) => {
  console.error('❌ Fatal error:', error);
  process.exit(1);
});
