import { promises as fs } from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const backendDir = path.resolve(__dirname, '..', '..');
const dataDir = path.join(backendDir, 'data');
const dataFile = path.join(dataDir, 'instance.json');

async function ensureDir() {
  await fs.mkdir(dataDir, { recursive: true });
}

export async function createInstanceId() {
  await ensureDir();
  const instanceId = randomUUID();
  const payload = {
    instanceId,
    startedAt: new Date().toISOString()
  };
  await fs.writeFile(dataFile, JSON.stringify(payload, null, 2), 'utf-8');
  return payload;
}

export async function readInstanceId() {
  await ensureDir();
  try {
    const raw = await fs.readFile(dataFile, 'utf-8');
    const parsed = JSON.parse(raw);
    if (parsed?.instanceId) {
      return parsed;
    }
  } catch {
    // ignore and recreate below
  }
  return createInstanceId();
}

