export function extractSvgString(input: unknown): string | null {
  if (typeof input === 'string') {
    if (input.trim().startsWith('<svg')) return input
    try {
      const j = JSON.parse(input)
      return (j?.svg || j?.data?.svg || null) as string | null
    } catch {
      return null
    }
  }
  if (input && typeof input === 'object') {
    const obj = input as Record<string, unknown>
    if (typeof obj.svg === 'string') return obj.svg
    if (obj.data && typeof (obj as any).data.svg === 'string') return (obj as any).data.svg
  }
  return null
}

export function ensureSvgDimensions(svg: string, width?: string | number, height?: string | number): string {
  const w = width === undefined ? undefined : typeof width === 'number' ? `${width}px` : width
  const h = height === undefined ? undefined : typeof height === 'number' ? `${height}px` : height
  if (!w && !h) return svg
  return svg.replace(/<svg(\s[^>]*)?>/i, (match) => {
    const hasW = /\swidth=/.test(match)
    const hasH = /\sheight=/.test(match)
    let m = match
    if (!hasW && w) m = m.replace(/<svg/i, `<svg width="${w}"`)
    if (!hasH && h) m = m.replace(/<svg/i, `<svg height="${h}"`)
    return m
  })
}


