import { FinishOptionsSchema } from './types.js'

export interface ValidationResult {
  valid: boolean
  data?: Record<string, unknown>
  blockers: string[]
  warnings: string[]
}

export function validate(spec: unknown): ValidationResult {
  const blockers: string[] = []
  const warnings: string[] = []

  try {
    const parsed = FinishOptionsSchema.parse(spec)

    // Validate branch name format if provided (pure string validation, no lib)
    if (parsed.branch) {
      if (parsed.branch.trim().length === 0) {
        blockers.push('Branch name cannot be empty')
      }
      if (parsed.branch.length > 100) {
        blockers.push('Branch name too long (max 100 characters)')
      }
      if (/[~^:?*\[\\]/.test(parsed.branch)) {
        blockers.push(`Branch name contains invalid characters: ${parsed.branch}`)
      }
      if (parsed.branch.startsWith('-') || parsed.branch.endsWith('.') || parsed.branch.endsWith('/') || parsed.branch.includes('..')) {
        blockers.push(`Branch name has invalid format: ${parsed.branch}`)
      }
    }

    return {
      valid: blockers.length === 0,
      data: parsed as Record<string, unknown>,
      blockers,
      warnings,
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err)
    blockers.push(`Invalid spec: ${message}`)
    return { valid: false, blockers, warnings }
  }
}
