import * as Log from "@saeeol/core/util/log"
import path from "path"
import { Global } from "@saeeol/core/global"
import z from "zod"
import fs from "fs"

const log = Log.create({ service: "saeeol.digest-storage" })

export const DigestSchema = z.object({
  project: z.string(),
  updated: z.number(),
  entities: z.array(z.object({
    name: z.string(),
    type: z.string(),
    observations: z.array(z.string()),
  })),
  relations: z.array(z.object({
    from: z.string(),
    to: z.string(),
    type: z.string(),
  })).optional(),
  summary: z.string().optional(),
})

export type Digest = z.infer<typeof DigestSchema>

function digestPath(): string {
  return path.join(Global.Path.data, "saeeol", "digests", "current.json")
}

export function readDigest(): Digest | null {
  try {
    const p = digestPath()
    if (!fs.existsSync(p)) return null
    const raw = fs.readFileSync(p, "utf-8")
    const parsed = DigestSchema.safeParse(JSON.parse(raw))
    if (!parsed.success) {
      log.info("digest parse error", { error: parsed.error.message })
      return null
    }
    return parsed.data
  } catch (e) {
    log.info("digest read error", { error: String(e) })
    return null
  }
}

export function writeDigest(digest: Digest): void {
  try {
    const p = digestPath()
    fs.mkdirSync(path.dirname(p), { recursive: true })
    fs.writeFileSync(p, JSON.stringify(digest, null, 2))
    log.info("digest saved", { entities: digest.entities.length })
  } catch (e) {
    log.info("digest write error", { error: String(e) })
  }
}
