

import * as fs from 'fs/promises';
import * as path from 'path';

// Define interfaces for the structured template
export interface IFormField {
  label: string;
  purpose?: string;
  details?: string;
}

export interface IFormSection {
  title: string;
  purpose?: string;
  fields: IFormField[];
}

export interface IReviewTemplate {
  sections: IFormSection[];
}

/**
 * Parses the BPCP CIM REVIEW TEMPLATE.md file into a structured JSON object.
 * This allows the agent to dynamically understand the sections and fields it needs to populate.
 * @param templateContent The raw markdown content of the template.
 * @returns A structured representation of the review template.
 */
export const parseCimReviewTemplate = (templateContent: string): IReviewTemplate => {
  const template: IReviewTemplate = { sections: [] };
  const lines = templateContent.split('\n');

  let currentSection: IFormSection | null = null;
  let currentField: IFormField | null = null;

  for (const line of lines) {
    const trimmedLine = line.trim();

    // Match section headers like (A) Deal Overview
    const sectionMatch = trimmedLine.match(/^\*\*\((.)\)\s+(.*)\*\*$/);
    if (sectionMatch) {
      if (currentSection) {
        template.sections.push(currentSection);
      }
      currentSection = {
        title: `(${sectionMatch[1]}) ${sectionMatch[2]}`,
        fields: [],
      };
      continue;
    }

    if (!currentSection) continue;

    // Match purpose lines
    const purposeMatch = trimmedLine.match(/^- \*\*Purpose:\*\* (.*)$/);
    if (purposeMatch && currentSection) {
      currentSection.purpose = purposeMatch[1] || '';
      continue;
    }

    // Match worksheet fields like - `Target Company Name:`
    const fieldMatch = trimmedLine.match(/^- `([^`]+):`\s*$/);
    if (fieldMatch && currentSection) {
      currentField = { label: (fieldMatch[1] || '').trim() };
      currentSection.fields.push(currentField);
      continue;
    }
    
    // Match worksheet fields with additional context like - `Deal Source:` - _Provides context..._
    const fieldWithContextMatch = trimmedLine.match(/^- `([^`]+):` - _(.*)_\s*$/);
    if (fieldWithContextMatch && currentSection) {
        currentField = { label: (fieldWithContextMatch[1] || '').trim(), details: (fieldWithContextMatch[2] || '').trim() };
        currentSection.fields.push(currentField);
        continue;
    }

    // Capture multi-line descriptions or notes for a field
    if (currentField && trimmedLine.startsWith('_') && trimmedLine.endsWith('_')) {
        currentField.details = (currentField.details ? currentField.details + ' ' : '') + trimmedLine.slice(1, -1);
    }
  }

  // Add the last section
  if (currentSection) {
    template.sections.push(currentSection);
  }

  // Special handling for the financial table as it's not a simple field
  const financialSection = template.sections.find(s => s.title.includes('Financial Summary'));
  if(financialSection) {
    financialSection.fields.push({
        label: 'Key Historical Financials Table',
        details: 'A table for Revenue, Gross Profit, and EBITDA over the last 3-4 years.'
    });
  }


  return template;
};

/**
 * Reads the template file from the filesystem and parses it.
 * @returns A promise that resolves to the structured review template.
 */
export const loadAndParseTemplate = async (): Promise<IReviewTemplate> => {
  // Path to the template file in the project root
  const templatePath = path.resolve(__dirname, '../../../BPCP CIM REVIEW TEMPLATE.md');
  const templateContent = await fs.readFile(templatePath, 'utf-8');
  return parseCimReviewTemplate(templateContent);
};

// Example of how to use it:
/*
(async () => {
  try {
    const reviewTemplate = await loadAndParseTemplate();
    console.log(JSON.stringify(reviewTemplate, null, 2));
  } catch (error) {
    console.error('Failed to load or parse template:', error);
  }
})();
*/
