import { backendGet } from '../../../../backend/node/client.js'
import { resourceContent } from '../../../protocol/index.js'
import type { MCPJSONValue, MCPResource } from '../../../protocol/types.js'
import { getMCPContextSnapshot } from '../focus/store.js'
import { listProjects } from './projects.js'
import { summarizeResource } from './summaries.js'

export function listProjectResources(): MCPResource[] {
  const snapshot = getMCPContextSnapshot()
  const resources: MCPResource[] = [
    {
      uri: 'movscript://projects',
      name: 'Projects',
      description: 'All visible MovScript projects.',
      mimeType: 'text/markdown',
    },
  ]

  if (snapshot.project) {
    const id = snapshot.project.id
    resources.push(
      resource(`movscript://project/${id}/summary`, 'Project summary'),
      resource(`movscript://project/${id}/scripts`, 'Scripts'),
      resource(`movscript://project/${id}/settings`, 'Settings'),
      resource(`movscript://project/${id}/assets`, 'Assets'),
      resource(`movscript://project/${id}/episodes`, 'Episodes'),
      resource(`movscript://project/${id}/scenes`, 'Scenes'),
      resource(`movscript://project/${id}/storyboards`, 'Storyboards'),
      resource(`movscript://project/${id}/shots`, 'Shots'),
    )
  }

  return resources
}

export const projectResourceReaders = [
  readProjectResource,
]

async function readProjectResource(uri: string): Promise<MCPJSONValue | null> {
  if (uri === 'movscript://projects') return resourceContent(uri, await listProjects({}))

  const projectResource = parseProjectResourceURI(uri)
  if (!projectResource) return null

  const data = await backendGet(projectResourceEndpoint(projectResource.projectId, projectResource.kind))
  return resourceContent(uri, summarizeResource(data))
}

function resource(uri: string, name: string): MCPResource {
  return { uri, name, mimeType: 'text/markdown' }
}

function projectResourceEndpoint(projectId: number, kind: string): string {
  switch (kind) {
    case 'summary':
      return `/projects/${projectId}`
    case 'assets':
    case 'assests':
      return `/projects/${projectId}/entities/asset-slots`
    case 'episodes':
      return `/projects/${projectId}/entities/productions`
    case 'scenes':
      return `/projects/${projectId}/entities/segments`
    case 'storyboards':
      return `/projects/${projectId}/entities/storyboard-scripts`
    case 'shots':
      return `/projects/${projectId}/entities/content-units`
    case 'settings':
      return `/projects/${projectId}/entities/settings`
    case 'scripts':
      return `/projects/${projectId}/${kind}`
    default:
      throw new Error(`Unsupported project resource kind: ${kind}`)
  }
}

function parseProjectResourceURI(uri: string): { projectId: number; kind: string } | null {
  const match = uri.match(/^movscript:\/\/project\/(\d+)\/([a-z-]+)$/)
  if (!match) return null
  return {
    projectId: Number(match[1]),
    kind: match[2] ?? '',
  }
}
