/**
 * Filesystem layout for the eye library.
 *
 * Layout:
 *   ~/.sandcode/eye/
 *   ├── awwwards/
 *   │   └── <slug>/
 *   │       ├── shot.webp
 *   │       ├── motion.webm
 *   │       ├── keyframes/00.webp … 09.webp
 *   │       ├── meta.json
 *   │       └── motion.json
 *   ├── user/<slug>/…
 *   └── filter.json
 */

import { readFile, writeFile, mkdir, stat, readdir } from 'fs/promises'
import { join } from 'path'
import { homedir } from 'os'
import {
  siteRecordSchema,
  type AwwwardsSite,
  type MotionDescriptors,
  type SiteRecord,
} from './types.js'

const EYE_ROOT = join(homedir(), '.sandcode', 'eye')
const AWWWARDS_ROOT = join(EYE_ROOT, 'awwwards')

export function getEyeRoot(): string {
  return EYE_ROOT
}

export function getAwwwardsSiteDir(slug: string): string {
  return join(AWWWARDS_ROOT, slug)
}

export async function ensureSiteDir(slug: string): Promise<string> {
  const dir = getAwwwardsSiteDir(slug)
  await mkdir(join(dir, 'keyframes'), { recursive: true })
  return dir
}

export async function siteExists(slug: string): Promise<boolean> {
  try {
    await stat(join(getAwwwardsSiteDir(slug), 'meta.json'))
    return true
  } catch {
    return false
  }
}

export async function getSiteAgeDays(slug: string): Promise<number | null> {
  try {
    const info = await stat(join(getAwwwardsSiteDir(slug), 'meta.json'))
    const ageMs = Date.now() - info.mtimeMs
    return ageMs / (1000 * 60 * 60 * 24)
  } catch {
    return null
  }
}

export async function writeSiteRecord(record: SiteRecord): Promise<void> {
  const dir = await ensureSiteDir(record.site.slug)
  await writeFile(join(dir, 'meta.json'), JSON.stringify(record, null, 2), 'utf-8')
}

export async function readSiteRecord(slug: string): Promise<SiteRecord | null> {
  try {
    const content = await readFile(join(getAwwwardsSiteDir(slug), 'meta.json'), 'utf-8')
    const parsed = JSON.parse(content) as unknown
    return siteRecordSchema.parse(parsed)
  } catch {
    return null
  }
}

export async function writeMotionDescriptors(
  slug: string,
  descriptors: MotionDescriptors,
): Promise<void> {
  const dir = await ensureSiteDir(slug)
  await writeFile(join(dir, 'motion.json'), JSON.stringify(descriptors, null, 2), 'utf-8')
}

export async function listIngestedSlugs(): Promise<string[]> {
  try {
    return await readdir(AWWWARDS_ROOT)
  } catch {
    return []
  }
}

export function buildInitialRecord(site: AwwwardsSite): SiteRecord {
  return {
    site,
    capturedAt: new Date().toISOString(),
    captureStatus: 'ok',
    filterState: 'unseen',
    captureErrors: [],
    files: {
      keyframes: [],
    },
  }
}
