import fs from "fs";
import path from "path";

export interface PersistedSession {
  id: string;
  name: string;
  type: string;
  status: 'idle' | 'running' | 'stopped';
  createdAt: string;
  logs: string[];
  workspaceRoot?: string;
  scopedDirs?: string[];
}

export class SessionPersister {
  private static workspaceRoot = process.cwd();

  private static getSessionsDir(): string {
    const dir = path.join(this.workspaceRoot, ".ai", "neural-loom", "sessions");
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    return dir;
  }

  public static saveSession(session: { id: string; name: string; type: string; status: string; createdAt: string; logs: string[]; workspaceRoot?: string; scopedDirs?: string[] }) {
    try {
      const dir = this.getSessionsDir();
      const filePath = path.join(dir, `${session.id}.json`);
      const data: PersistedSession = {
        id: session.id,
        name: session.name,
        type: session.type,
        status: (session.status === 'running' && session.type === 'mock') ? 'running' : session.status as 'idle' | 'running' | 'stopped', // Mock sessions can persist as running or restart
        createdAt: session.createdAt,
        logs: session.logs,
        workspaceRoot: session.workspaceRoot,
        scopedDirs: session.scopedDirs
      };
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
    } catch (err) {
      console.error(`[SessionPersister] Failed to save session ${session.id}:`, err);
    }
  }

  public static loadAllSessions(): PersistedSession[] {
    try {
      const dir = this.getSessionsDir();
      const files = fs.readdirSync(dir);
      const sessions: PersistedSession[] = [];

      for (const file of files) {
        if (file.endsWith(".json")) {
          const filePath = path.join(dir, file);
          const raw = fs.readFileSync(filePath, "utf8");
          const data: PersistedSession = JSON.parse(raw);
          // On server restart, active PTY processes (which are dead) are marked stopped
          if (data.status === "running" && data.type !== "mock") {
            data.status = "stopped";
            data.logs.push("\r\n\x1b[1;31m[System] Server restarted. Terminal connection lost.\x1b[0m\r\n");
            // Save the updated status back to disk
            fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
          }
          sessions.push(data);
        }
      }
      return sessions;
    } catch (err) {
      console.error("[SessionPersister] Failed to load sessions:", err);
      return [];
    }
  }

  public static deleteSession(id: string) {
    try {
      const dir = this.getSessionsDir();
      const filePath = path.join(dir, `${id}.json`);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    } catch (err) {
      console.error(`[SessionPersister] Failed to delete session ${id}:`, err);
    }
  }
}
