const express = require("express");
const fs = require("fs");
const path = require("path");

const app = express();
const PORT = process.env.PORT || 3000;
const DATA_FILE = process.env.DATA_FILE || "/data/progress.json";

app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));

// Ensure data directory and file exist
function ensureDataFile() {
  const dir = path.dirname(DATA_FILE);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  if (!fs.existsSync(DATA_FILE)) fs.writeFileSync(DATA_FILE, JSON.stringify({}));
}

// GET progress
app.get("/api/progress", (req, res) => {
  try {
    ensureDataFile();
    const data = JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
    res.json(data);
  } catch (err) {
    console.error("Read error:", err);
    res.status(500).json({ error: "Failed to read progress" });
  }
});

// POST progress (full state)
app.post("/api/progress", (req, res) => {
  try {
    ensureDataFile();
    fs.writeFileSync(DATA_FILE, JSON.stringify(req.body, null, 2));
    res.json({ ok: true });
  } catch (err) {
    console.error("Write error:", err);
    res.status(500).json({ error: "Failed to save progress" });
  }
});

app.listen(PORT, () => console.log(`Podcast checklist running on port ${PORT}`));
