/**
 * Terraform Renderer
 * Wrapper for template engine Terraform rendering
 */

import { Template } from '../services/template.js'
import { templateEngine, RenderOptions } from '../services/template-engine.js'
import { logger } from './logger.js'

export class TerraformRenderer {
  /**
   * Render template to Terraform HCL
   */
  async render(template: Template, options: RenderOptions = {}): Promise<string> {
    try {
      logger.info('Rendering template to Terraform', {
        templateId: template.id,
        templateType: template.templateType,
      })

      if (template.templateType === 'PTF') {
        return templateEngine.renderToTerraform(template, options)
      }

      if (template.templateType === 'TERRAFORM') {
        // Already Terraform, just interpolate parameters
        return this.interpolateTerraform(template.content, options.parameters || {})
      }

      throw new Error(`Cannot render template type ${template.templateType} to Terraform`)
    } catch (error) {
      logger.error('Failed to render template to Terraform', {
        templateId: template.id,
        error: error instanceof Error ? error.message : String(error),
      })
      throw error
    }
  }

  /**
   * Interpolate parameters in existing Terraform content
   */
  private interpolateTerraform(content: string, parameters: Record<string, any>): string {
    // Simple interpolation: ${param.name} -> value
    return content.replace(/\$\{([^}]+)\}/g, (match, paramName) => {
      const value = parameters[paramName.trim()]
      if (value === undefined) {
        logger.warn(`Parameter "${paramName.trim()}" not found, keeping placeholder`, {
          paramName: paramName.trim(),
        })
        return match
      }
      return String(value)
    })
  }

  /**
   * Validate Terraform syntax (basic check)
   */
  validateSyntax(terraformContent: string): { valid: boolean; errors: string[] } {
    const errors: string[] = []

    // Basic validation - check for balanced braces
    const openBraces = (terraformContent.match(/\{/g) || []).length
    const closeBraces = (terraformContent.match(/\}/g) || []).length

    if (openBraces !== closeBraces) {
      errors.push(`Unbalanced braces: ${openBraces} open, ${closeBraces} close`)
    }

    // Check for basic syntax issues
    const lines = terraformContent.split('\n')
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim()
      // Check for unterminated strings
      if (line.includes('"') && (line.match(/"/g) || []).length % 2 !== 0) {
        errors.push(`Unterminated string on line ${i + 1}`)
      }
    }

    return {
      valid: errors.length === 0,
      errors,
    }
  }
}

export const terraformRenderer = new TerraformRenderer()

