/**
 * Session → Markdown export. Converts a session's messages (with structured
 * blocks) into a single Markdown document and triggers a download.
 */

interface ExportBlock {
  type: string
  text?: string
  name?: string
  id?: string
  input?: Record<string, unknown>
  content?: string
  is_error?: boolean
  tool_use_id?: string
  parent_tool_use_id?: string
  blocks?: ExportBlock[]
}

interface ExportData {
  session: { title: string; model: string; workspace: string; created_at: string }
  messages: { role: string; text?: string; blocks?: ExportBlock[]; created_at: string }[]
}

function getExportToolSummary(name: string, input: Record<string, unknown>): string {
  switch (name) {
    case 'Read': return String(input.file_path || input.path || '').split('/').pop() || ''
    case 'Write': return String(input.file_path || input.path || '').split('/').pop() || ''
    case 'Edit': return String(input.file_path || input.path || '').split('/').pop() || ''
    case 'Bash': return `\`${String(input.command || '').slice(0, 80)}\``
    case 'Glob': return String(input.pattern || '')
    case 'Grep': return String(input.pattern || '')
    case 'WebSearch': return String(input.query || '')
    case 'WebFetch': return String(input.url || '').slice(0, 60)
    case 'Agent': return String(input.prompt || '').slice(0, 80)
    default: return ''
  }
}

function renderBlocks(blocks: ExportBlock[], lines: string[], indent: string) {
  for (const b of blocks) {
    switch (b.type) {
      case 'text':
        if (b.text) {
          // Indent each line for nested blocks
          if (indent) {
            for (const line of b.text.split('\n')) {
              lines.push(indent + line)
            }
          } else {
            lines.push(b.text)
          }
          lines.push('')
        }
        break

      case 'thinking':
        lines.push(`${indent}> *Thinking*`)
        if (b.text) {
          for (const line of b.text.split('\n')) {
            lines.push(`${indent}> ${line}`)
          }
        }
        lines.push('')
        break

      case 'tool_use': {
        const summary = getExportToolSummary(b.name || '', b.input || {})
        lines.push(`${indent}**Tool: \`${b.name}\`**${summary ? ` — ${summary}` : ''}`)
        lines.push('')
        break
      }

      case 'tool_result':
        if (b.content) {
          lines.push(`${indent}<details><summary>${b.is_error ? 'Error Result' : 'Result'}</summary>`)
          lines.push('')
          lines.push(`${indent}\`\`\``)
          for (const line of b.content.split('\n')) {
            lines.push(indent + line)
          }
          lines.push(`${indent}\`\`\``)
          lines.push('')
          lines.push(`${indent}</details>`)
          lines.push('')
        }
        break

      case 'agent_content':
        if (b.blocks && b.blocks.length > 0) {
          lines.push(`${indent}> **Sub-Agent**`)
          lines.push('')
          renderBlocks(b.blocks, lines, indent + '> ')
        }
        break

      // tool_progress, permission_request, tool_raw_result — skip
      default:
        break
    }
  }
}

function convertSessionToMarkdown(data: ExportData): string {
  const lines: string[] = []
  const s = data.session

  // Header
  lines.push(`# ${s.title}`)
  lines.push('')
  lines.push(`- **Model**: ${s.model}`)
  lines.push(`- **Workspace**: ${s.workspace}`)
  lines.push(`- **Created**: ${s.created_at}`)
  lines.push('')
  lines.push('---')
  lines.push('')

  for (const msg of data.messages) {
    const ts = msg.created_at ? new Date(msg.created_at).toLocaleString() : ''
    if (msg.role === 'user') {
      lines.push(`## User (${ts})`)
      lines.push('')
      lines.push(msg.text || '')
      lines.push('')
    } else {
      lines.push(`## Assistant (${ts})`)
      lines.push('')
      if (msg.blocks) {
        renderBlocks(msg.blocks, lines, '')
      }
    }
  }

  return lines.join('\n')
}

/** Fetch a session's export data and download it as a .md file. */
export async function exportSession(sessionId: string, title: string) {
  try {
    const res = await fetch(`/api/sessions/${sessionId}/export`)
    if (!res.ok) return
    const data = await res.json()
    const md = convertSessionToMarkdown(data)
    const blob = new Blob([md], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${title.replace(/[^a-zA-Z0-9一-鿿_-]/g, '_').slice(0, 50)}.md`
    a.click()
    URL.revokeObjectURL(url)
  } catch { /* ignore */ }
}
