import type { AppliedDataSemantic } from '../Semantics.js'
import { SemanticType } from '../Semantics.js'

/**
 * Configuration options for the Markdown semantic.
 * Controls rendering, sanitization, and allowed features.
 */
export interface MarkdownConfig {
  /**
   * List of allowed HTML tags in the rendered output.
   */
  allowedTags?: string[]
  /**
   * Sanitization level: 'strict', 'moderate', or 'none'.
   */
  sanitizeLevel?: 'strict' | 'moderate' | 'none'
  /**
   * Whether to allow images in markdown.
   */
  allowImages?: boolean
  /**
   * Whether to allow links in markdown.
   */
  allowLinks?: boolean
  /**
   * Whether to allow tables in markdown.
   */
  allowTables?: boolean
  /**
   * Whether to allow raw HTML in markdown.
   */
  allowHtml?: boolean
  /**
   * Whether to allow footnotes in markdown.
   */
  allowFootnotes?: boolean
  /**
   * Whether to allow GitHub-style task lists.
   */
  allowTaskLists?: boolean
  /**
   * Whether to allow strikethrough formatting.
   */
  allowStrikethrough?: boolean
  /**
   * Whether to allow math expressions (e.g., LaTeX).
   */
  allowMath?: boolean
  /**
   * Custom metadata for the markdown field.
   */
  metadata?: Record<string, unknown>
  /**
   * Index signature to allow additional properties.
   */
  [key: string]: unknown
}

/**
 * Type-safe configuration for Markdown semantic.
 */
export interface AppliedMarkdownSemantic extends AppliedDataSemantic {
  id: SemanticType.Markdown
  config?: MarkdownConfig
}

/**
 * Type guard to check if a semantic is a Markdown semantic.
 */
export const isMarkdownSemantic = (semantic: AppliedDataSemantic): semantic is AppliedMarkdownSemantic => {
  return semantic.id === SemanticType.Markdown
}

/**
 * Helper function to create a Markdown semantic with configuration.
 */
export const createMarkdownSemantic = (config: MarkdownConfig = {}): AppliedMarkdownSemantic => {
  const mergedConfig = {
    ...DEFAULT_MARKDOWN_CONFIG,
    ...config,
  }
  if (config.metadata) {
    mergedConfig.metadata = { ...config.metadata }
  }

  return {
    id: SemanticType.Markdown,
    config: mergedConfig,
  }
}

/**
 * Default configuration for Markdown semantic.
 */
export const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig = {
  allowedTags: ['b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'p', 'br', 'pre', 'code'],
  sanitizeLevel: 'strict',
  allowImages: true,
  allowLinks: true,
  allowTables: true,
  allowHtml: false,
  allowFootnotes: false,
  allowTaskLists: false,
  allowStrikethrough: true,
  allowMath: false,
}
