import cors from 'cors'
import express from 'express'
import { join } from 'path'
import { HttpStatusCode } from '@peertube/peertube-models'
import { CONFIG } from '@server/initializers/config.js'
import { EventModel } from '@server/models/video/event.js'
import { LiveVideoModel } from '@server/models/video/live-video.js'
import { FILES_CACHE, LAZY_STATIC_PATHS, STATIC_MAX_AGE } from '../initializers/constants.js'
import {
  AvatarPermanentFileCache,
  VideoCaptionsSimpleFileCache,
  VideoMiniaturePermanentFileCache,
  VideoPreviewsSimpleFileCache,
  VideoStoryboardsSimpleFileCache,
  VideoTorrentsSimpleFileCache
} from '../lib/files-cache/index.js'
import { asyncMiddleware, handleStaticError } from '../middlewares/index.js'

// ---------------------------------------------------------------------------
// Cache initializations
// ---------------------------------------------------------------------------

VideoPreviewsSimpleFileCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
VideoCaptionsSimpleFileCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
VideoTorrentsSimpleFileCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
VideoStoryboardsSimpleFileCache.Instance.init(CONFIG.CACHE.STORYBOARDS.SIZE, FILES_CACHE.STORYBOARDS.MAX_AGE)

// ---------------------------------------------------------------------------

const lazyStaticRouter = express.Router()

lazyStaticRouter.use(cors())

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.AVATARS + ':filename',
  asyncMiddleware(getActorImage),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.BANNERS + ':filename',
  asyncMiddleware(getActorImage),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.THUMBNAILS + ':filename',
  asyncMiddleware(getThumbnail),
  handleStaticError
)

// Event thumbnails - serve directly from filesystem without database lookup
lazyStaticRouter.use(
  '/lazy-static/event-thumbnails/:filename',
  asyncMiddleware(getEventThumbnail),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.PREVIEWS + ':filename',
  asyncMiddleware(getPreview),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.STORYBOARDS + ':filename',
  asyncMiddleware(getStoryboard),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.VIDEO_CAPTIONS + ':filename',
  asyncMiddleware(getVideoCaption),
  handleStaticError
)

lazyStaticRouter.use(
  LAZY_STATIC_PATHS.TORRENTS + ':filename',
  asyncMiddleware(getTorrent),
  handleStaticError
)

// ---------------------------------------------------------------------------

export {
  lazyStaticRouter
}

// ---------------------------------------------------------------------------
const avatarPermanentFileCache = new AvatarPermanentFileCache()

function getActorImage (req: express.Request, res: express.Response, next: express.NextFunction) {
  const filename = req.params.filename

  return avatarPermanentFileCache.lazyServe({ filename, res, next })
}

// ---------------------------------------------------------------------------
const videoMiniaturePermanentFileCache = new VideoMiniaturePermanentFileCache()

function getThumbnail (req: express.Request, res: express.Response, next: express.NextFunction) {
  const filename = req.params.filename

  return serveSpecialThumbnailOrFallback({
    filename,
    fallback: () => videoMiniaturePermanentFileCache.lazyServe({ filename, res, next }),
    res
  })
}

// ---------------------------------------------------------------------------

async function getEventThumbnail (req: express.Request, res: express.Response) {
  const filename = req.params.filename
  const event = await EventModel.loadByThumbnailFilename(filename)

  console.log('event thumbnail debug', {
    filename,
    found: !!event,
    mime: event?.thumbnailMimeType,
    size: event?.thumbnailSize,
    hasData: !!event?.thumbnailData,
    dataLength: event?.thumbnailData ? event.thumbnailData.length : null
  })

  if (event?.thumbnailData) return sendSpecialThumbnail({
    data: event.thumbnailData,
    mimeType: event.thumbnailMimeType,
    etag: event.thumbnailEtag,
    size: event.thumbnailSize,
    res
  })

  const path = join(CONFIG.STORAGE.THUMBNAILS_DIR, filename)
  
  return res.sendFile(path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER }, (err: any) => {
    if (err) {
      return res.status(HttpStatusCode.NOT_FOUND_404).end()
    }
  })
}

async function serveSpecialThumbnailOrFallback (options: {
  filename: string
  fallback: () => Promise<any>
  res: express.Response
}) {
  const { filename, fallback, res } = options
  const liveVideo = await LiveVideoModel.loadByThumbnailFilename(filename)

  if (liveVideo?.thumbnailData) return sendSpecialThumbnail({
    data: liveVideo.thumbnailData,
    mimeType: liveVideo.thumbnailMimeType,
    etag: liveVideo.thumbnailEtag,
    size: liveVideo.thumbnailSize,
    res
  })

  return fallback()
}

function sendSpecialThumbnail (options: {
  data: Buffer
  mimeType: string
  etag: string
  size: number
  res: express.Response
}) {
  const { data, mimeType, etag, size, res } = options

  res.contentType(mimeType)
  res.setHeader('Cache-Control', 'public, max-age=172800')
  if (etag) res.setHeader('ETag', etag)
  if (size !== null && size !== undefined) res.setHeader('Content-Length', size.toString())

  return res.status(HttpStatusCode.OK_200).send(data)
}

// ---------------------------------------------------------------------------

async function getPreview (req: express.Request, res: express.Response) {
  const result = await VideoPreviewsSimpleFileCache.Instance.getFilePath(req.params.filename)
  if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()

  return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
}

async function getStoryboard (req: express.Request, res: express.Response) {
  const result = await VideoStoryboardsSimpleFileCache.Instance.getFilePath(req.params.filename)
  if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()

  return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
}

async function getVideoCaption (req: express.Request, res: express.Response) {
  const result = await VideoCaptionsSimpleFileCache.Instance.getFilePath(req.params.filename)
  if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()

  return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
}

async function getTorrent (req: express.Request, res: express.Response) {
  const result = await VideoTorrentsSimpleFileCache.Instance.getFilePath(req.params.filename)
  if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()

  return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.SERVER })
}
