import { InvoiceFormat } from '../../interfaces/common.js';
import { DOMParser } from 'xmldom';

/**
 * Utility class for detecting invoice formats
 */
export class FormatDetector {
  /**
   * Detects the format of an XML document
   * @param xml XML content to analyze
   * @returns Detected invoice format
   */
  public static detectFormat(xml: string): InvoiceFormat {
    try {
      const doc = new DOMParser().parseFromString(xml, 'application/xml');
      const root = doc.documentElement;

      if (!root) {
        return InvoiceFormat.UNKNOWN;
      }

      // UBL detection (Invoice or CreditNote root element)
      if (root.nodeName === 'Invoice' || root.nodeName === 'CreditNote') {
        // For simplicity, we'll treat all UBL documents as XRechnung for now
        // In a real implementation, we would check for specific customization IDs
        return InvoiceFormat.XRECHNUNG;
      }

      // Factur-X/ZUGFeRD detection (CrossIndustryInvoice root element)
      if (root.nodeName === 'rsm:CrossIndustryInvoice' || root.nodeName === 'CrossIndustryInvoice') {
        // For simplicity, we'll treat all CII documents as Factur-X for now
        // In a real implementation, we would check for specific profiles
        return InvoiceFormat.FACTURX;
      }

      // FatturaPA detection would be implemented here
      if (root.nodeName === 'FatturaElettronica' ||
          (root.getAttribute('xmlns') && root.getAttribute('xmlns')!.includes('fatturapa.gov.it'))) {
        return InvoiceFormat.FATTURAPA;
      }

      return InvoiceFormat.UNKNOWN;
    } catch (error) {
      console.error('Error detecting format:', error);
      return InvoiceFormat.UNKNOWN;
    }
  }
}