// Agreement Validator Service
// Validates agreement content and structure

export interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings: string[];
}

export class AgreementValidator {
  /**
   * Validate agreement
   */
  async validate(agreementContent: string, variables: Record<string, any>): Promise<ValidationResult> {
    const errors: string[] = [];
    const warnings: string[] = [];

    // Check for required sections
    const requiredSections = [
      'Grant of IRU',
      'Capacity Tier',
      'Term',
      'Fees',
      'Governing Law',
    ];

    for (const section of requiredSections) {
      if (!agreementContent.includes(section)) {
        errors.push(`Missing required section: ${section}`);
      }
    }

    // Check for unresolved variables
    const unresolvedVariables = agreementContent.match(/\{\{([^}]+)\}\}/g);
    if (unresolvedVariables) {
      unresolvedVariables.forEach((variable) => {
        const varName = variable.replace(/\{\{|\}\}/g, '');
        if (!this.hasVariable(variables, varName)) {
          warnings.push(`Unresolved variable: ${variable}`);
        }
      });
    }

    // Check for required variables
    const requiredVariables = ['participantName', 'capacityTier', 'jurisdiction'];
    for (const varName of requiredVariables) {
      if (!variables[varName]) {
        errors.push(`Missing required variable: ${varName}`);
      }
    }

    // Validate agreement length
    if (agreementContent.length < 1000) {
      warnings.push('Agreement content seems too short');
    }

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

  /**
   * Check if variable exists (supports nested paths)
   */
  private hasVariable(variables: Record<string, any>, path: string): boolean {
    if (path.includes('.')) {
      const parts = path.split('.');
      let current: any = variables;
      for (const part of parts) {
        if (current && typeof current === 'object' && part in current) {
          current = current[part];
        } else {
          return false;
        }
      }
      return true;
    }
    return path in variables;
  }
}

export const agreementValidator = new AgreementValidator();
