import { NextRequest, NextResponse } from 'next/server'
import { isAuthError, requireWorkspaceReadAccess } from '@/lib/auth/session'
import { getWorkspacePath, getProjectPath, GLOBAL_WORKSPACE_ID } from '@/lib/workspace-fs'
import fs from 'fs'
import path from 'path'

interface SkillTreeNode {
  name: string
  type: 'file' | 'folder'
  path: string
  children?: SkillTreeNode[]
  enabled?: boolean
}

function getEntryType(entryPath: string, entry: fs.Dirent): 'file' | 'folder' | null {
  if (entry.isDirectory()) return 'folder'
  if (entry.isFile()) return 'file'
  if (!entry.isSymbolicLink()) return null

  try {
    const stat = fs.statSync(entryPath)
    if (stat.isDirectory()) return 'folder'
    if (stat.isFile()) return 'file'
  } catch {
    return null
  }

  return null
}

function buildSkillsTree(dirPath: string, basePath = '', maxDepth = 6, depth = 0): SkillTreeNode[] {
  if (depth >= maxDepth || !fs.existsSync(dirPath)) return []

  const entries = fs.readdirSync(dirPath, { withFileTypes: true })
    .filter(e => !e.name.startsWith('.'))
    .sort((a, b) => {
      const aType = getEntryType(path.join(dirPath, a.name), a)
      const bType = getEntryType(path.join(dirPath, b.name), b)
      if (aType === 'folder' && bType !== 'folder') return -1
      if (aType !== 'folder' && bType === 'folder') return 1
      return a.name.localeCompare(b.name)
    })

  const tree: SkillTreeNode[] = []

  for (const entry of entries) {
    const relPath = basePath ? `${basePath}/${entry.name}` : entry.name
    const entryPath = path.join(dirPath, entry.name)
    const entryType = getEntryType(entryPath, entry)
    if (entryType === 'folder') {
      // Check if skill folder has SKILL.md → mark as enabled
      const skillMd = path.join(entryPath, 'SKILL.md')
      const hasSkillMd = fs.existsSync(skillMd)
      let enabled: boolean | undefined
      if (hasSkillMd) {
        // Parse enabled from frontmatter
        try {
          const content = fs.readFileSync(skillMd, 'utf-8')
          enabled = !content.includes('enabled: false')
        } catch {
          enabled = true
        }
      }
      tree.push({
        name: entry.name,
        type: 'folder' as const,
        path: relPath,
        children: buildSkillsTree(entryPath, relPath, maxDepth, depth + 1),
        ...(hasSkillMd && { enabled }),
      })
      continue
    }
    if (entryType === 'file') {
      tree.push({ name: entry.name, type: 'file' as const, path: relPath })
    }
  }

  return tree
}

// GET /api/workspaces/[id]/skills-tree — full directory tree of .claude/skills/
export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  let access
  try { access = await requireWorkspaceReadAccess(id) } catch (err) { if (isAuthError(err)) return err; throw err }

  try {
    // Check if project folder still exists (skip for global workspace)
    if (id !== GLOBAL_WORKSPACE_ID) {
      try {
        const projectPath = getProjectPath(id)
        if (!fs.existsSync(projectPath)) return NextResponse.json({ tree: [] })
      } catch {
        return NextResponse.json({ tree: [] })
      }
    }
    const skillsDir = path.join(getWorkspacePath(id, access.user.id), 'skills')
    const tree = buildSkillsTree(skillsDir)
    return NextResponse.json({ tree })
  } catch {
    return NextResponse.json({ tree: [] })
  }
}
