import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
import { randomUUID } from "crypto"
import { join } from "path"

const DATA_DIR = join(process.cwd(), "data")
const DATA_FILE = join(DATA_DIR, "videos.json")

export interface Video {
  id: string
  title: string
  description: string
  youtubeUrl: string
  thumbnail: string
  createdAt: string
}

function ensureDataDir() {
  if (!existsSync(DATA_DIR)) {
    mkdirSync(DATA_DIR, { recursive: true })
  }
}

function seedDefaultVideos(): Video[] {
  return [
    {
      id: randomUUID(),
      title: "Getting Started with Your Android Box",
      description: "Learn how to set up your new Android box and connect it to your TV",
      youtubeUrl: "#",
      thumbnail: "/images/android-box-setup.jpg",
      createdAt: new Date().toISOString(),
    },
    {
      id: randomUUID(),
      title: "Installing Apps and Adding Channels",
      description: "Step-by-step guide to installing your favorite streaming apps",
      youtubeUrl: "#",
      thumbnail: "/images/android-apps-streaming.jpg",
      createdAt: new Date().toISOString(),
    },
    {
      id: randomUUID(),
      title: "Troubleshooting Common Issues",
      description: "Quick fixes for buffering, connection issues, and more",
      youtubeUrl: "#",
      thumbnail: "/images/troubleshooting-tech-support.jpg",
      createdAt: new Date().toISOString(),
    },
    {
      id: randomUUID(),
      title: "Optimizing Your Streaming Experience",
      description: "Tips and tricks to get the best performance from your box",
      youtubeUrl: "#",
      thumbnail: "/images/streaming-optimization.jpg",
      createdAt: new Date().toISOString(),
    },
    {
      id: randomUUID(),
      title: "Using the Remote Control",
      description: "Master all the features of your remote control",
      youtubeUrl: "#",
      thumbnail: "/images/remote-control-android.jpg",
      createdAt: new Date().toISOString(),
    },
    {
      id: randomUUID(),
      title: "Advanced Settings and Customization",
      description: "Customize your Android box to match your viewing preferences",
      youtubeUrl: "#",
      thumbnail: "/images/android-settings-customization.jpg",
      createdAt: new Date().toISOString(),
    },
  ]
}

export function getVideos(): Video[] {
  ensureDataDir()
  if (!existsSync(DATA_FILE)) {
    const defaults = seedDefaultVideos()
    writeFileSync(DATA_FILE, JSON.stringify(defaults, null, 2))
    return defaults
  }
  const raw = readFileSync(DATA_FILE, "utf-8")
  return JSON.parse(raw)
}

export function addVideo(video: Omit<Video, "id" | "createdAt">): Video {
  const videos = getVideos()
  const newVideo: Video = {
    ...video,
    id: randomUUID(),
    createdAt: new Date().toISOString(),
  }
  videos.unshift(newVideo)
  writeFileSync(DATA_FILE, JSON.stringify(videos, null, 2))
  return newVideo
}

export function deleteVideo(id: string): boolean {
  const videos = getVideos()
  const filtered = videos.filter((v) => v.id !== id)
  if (filtered.length === videos.length) return false
  writeFileSync(DATA_FILE, JSON.stringify(filtered, null, 2))
  return true
}

export function extractYoutubeId(url: string): string | null {
  const patterns = [
    /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,
    /youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/,
  ]
  for (const pattern of patterns) {
    const match = url.match(pattern)
    if (match) return match[1]
  }
  return null
}

export function getYoutubeThumbnail(youtubeUrl: string): string {
  const videoId = extractYoutubeId(youtubeUrl)
  if (videoId) {
    return `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`
  }
  return "/images/android-box-setup.jpg"
}
