import fs from 'fs/promises';
import path from 'path';

const sessionsDir = path.join(process.cwd(), 'sessions');

let currentContext: any = {};

const generateSpecId = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const randomId = Math.random().toString(36).substring(2, 6).toUpperCase();
  return `SPEC-${year}${month}${day}-${randomId}`;
};

export const createContext = (featurePrompt: string) => {
  const specId = generateSpecId();
  currentContext = {
    specId,
    featurePrompt,
    spec: {},
    agents: {},
    finalBundle: {},
  };
  return currentContext;
};

export const getContext = () => currentContext;

export const updateContext = (updates: any) => {
  currentContext = { ...currentContext, ...updates };
  return currentContext;
};

export const saveContext = async () => {
  const filePath = path.join(sessionsDir, `${currentContext.specId}.json`);
  await fs.writeFile(filePath, JSON.stringify(currentContext, null, 2));
  return filePath;
};

export const loadContext = async (specId: string) => {
  const filePath = path.join(sessionsDir, `${specId}.json`);
  const data = await fs.readFile(filePath, 'utf-8');
  currentContext = JSON.parse(data);
  return currentContext;
};
