import {
  FlaskConical,
  Activity,
  Box,
  RefreshCw,
  CheckCircle2,
  BarChart3,
  Sparkles,
} from "lucide-react"

export const TYPE_CONFIG = {
  test_generation: { icon: FlaskConical },
  optimization: { icon: Box },
  line_profiler: { icon: Activity },
  refinement: { icon: RefreshCw },
  adaptive: { icon: Sparkles },
  ranking: { icon: BarChart3 },
  summary: { icon: CheckCircle2 },
}

export function formatTime(ms: number): string {
  if (ms < 1000) return `${Math.round(ms)}ms`
  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
  return `${(ms / 60000).toFixed(1)}m`
}

export function stripCodeHeader(code: string): string {
  const lines = code.split("\n")

  // Remove opening fence if present
  const hasOpeningFence = lines[0] && /^`{3}[a-z]*(:.*)?$/i.test(lines[0].trim())
  const startIndex = hasOpeningFence ? 1 : 0

  // Remove closing fence if present
  const lastLine = lines[lines.length - 1]
  const hasClosingFence = lines.length > 0 && lastLine?.trim() === "```"
  const endIndex = hasClosingFence ? lines.length - 1 : lines.length

  return lines.slice(startIndex, endIndex).join("\n")
}

export interface ParsedCodeBlock {
  language: string
  filename: string | null
  path: string | null
  code: string
  lineCount: number
}

export function parseCodeBlock(rawCode: string): ParsedCodeBlock {
  const markdownMatch = rawCode.match(/^```(\w+)(?::([^\n]+))?\n([\s\S]*?)```\s*$/)

  if (markdownMatch) {
    const [, language, path, code] = markdownMatch
    const trimmedCode = code.trimEnd()
    const filename = path ? path.split("/").pop() || null : null

    return {
      language: language || "python",
      filename,
      path: path || null,
      code: trimmedCode,
      lineCount: trimmedCode.split("\n").length,
    }
  }

  return {
    language: "python",
    filename: null,
    path: null,
    code: rawCode,
    lineCount: rawCode.split("\n").length,
  }
}

export function parseAllCodeBlocks(markdown: string): ParsedCodeBlock[] {
  const files: ParsedCodeBlock[] = []
  const regex = /```(\w+)(?::([^\n]+))?\n([\s\S]*?)```/g
  let match

  while ((match = regex.exec(markdown)) !== null) {
    const [, language, path, code] = match
    const filename = path ? path.split("/").pop() || null : null
    const trimmedCode = code.trimEnd()
    files.push({
      path: path || null,
      filename,
      language: language || "python",
      code: trimmedCode,
      lineCount: trimmedCode.split("\n").length,
    })
  }

  if (files.length === 0 && markdown.trim()) {
    return [parseCodeBlock(markdown)]
  }

  return files
}

export function findMatchingFile(
  files: ParsedCodeBlock[],
  targetPath: string | null
): ParsedCodeBlock | null {
  if (!targetPath || files.length === 0) {
    return files[0] || null
  }

  // Try exact path match first
  const exactMatch = files.find(f => f.path === targetPath)
  if (exactMatch) return exactMatch

  // Try filename match
  const targetFilename = targetPath.split("/").pop()
  const filenameMatch = files.find(f => f.filename === targetFilename)
  if (filenameMatch) return filenameMatch

  // Try partial path match
  const partialMatch = files.find(f => {
    return f.path && (targetPath.endsWith(f.path) || f.path.endsWith(targetPath))
  })
  if (partialMatch) return partialMatch

  // Fall back to first file
  return files[0] || null
}
