/**
 * PR-A Baseline Test 02: Session Creation
 * Verifies: sessions can be created, read, and have persistent state
 * Freezes: session creation contract
 */

import { describe, it } from "node:test";
import assert from "node:assert";
import { execSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";

const AGENTS_HOME = join(homedir(), ".openclaw");
const SESSIONS_DIR = join(AGENTS_HOME, "agents", "main", "sessions");

describe("test-02: Session Creation Baseline", () => {
  it("02.01 - sessions directory exists", () => {
    const exists = existsSync(SESSIONS_DIR);
    console.log("[BASELINE] sessions dir:", SESSIONS_DIR);
    console.log("[BASELINE] sessions dir exists:", exists);
    // Directory might not exist if no sessions created yet — that's valid baseline
    if (!exists) {
      console.log("[BASELINE] No sessions directory — no sessions created yet (valid baseline)");
    }
    assert.ok(true, "baseline frozen: sessions dir check");
  });

  it("02.02 - can list existing sessions", () => {
    const out = execSync("openclaw status --json 2>/dev/null", {
      timeout: 15000,
      encoding: "utf8",
    }).trim();
    try {
      const s = JSON.parse(out);
      console.log("[BASELINE] sessions count:", s.sessionCount ?? "unknown");
      assert.ok(typeof s === "object", "status must be an object");
    } catch {
      // Text output is fine
      assert.ok(out.length > 0, "status must produce output");
    }
  });

  it("02.03 - session store directory structure recorded", () => {
    if (existsSync(SESSIONS_DIR)) {
      const files = readdirSync(SESSIONS_DIR).filter(
        (f) => f.endsWith(".json") || f.endsWith(".md")
      );
      console.log("[BASELINE] session files count:", files.length);
      console.log("[BASELINE] session file types:", 
        [...new Set(files.map(f => f.slice(f.lastIndexOf('.'))))].join(", "));
      assert.ok(Array.isArray(files), "session files must be listable");
    } else {
      console.log("[BASELINE] No session files to inspect (valid baseline)");
    }
    assert.ok(true, "baseline frozen: session dir structure");
  });

  it("02.04 - workspace files are accessible (session context)", () => {
    const workspaceDir = join(AGENTS_HOME, "workspace");
    const keyFiles = ["AGENTS.md", "SOUL.md", "MEMORY.md"];
    for (const f of keyFiles) {
      const path = join(workspaceDir, f);
      const exists = existsSync(path);
      const size = exists ? readFileSync(path, "utf8").length : 0;
      console.log(`[BASELINE] workspace/${f}: exists=${exists}, size=${size}`);
    }
    assert.ok(existsSync(join(workspaceDir, "AGENTS.md")), "AGENTS.md must exist");
    assert.ok(existsSync(join(workspaceDir, "MEMORY.md")), "MEMORY.md must exist");
  });

  it("02.05 - session write lock mechanism exists", () => {
    // Check if proper-lockfile is available (used for session locking)
    try {
      require.resolve("proper-lockfile");
      console.log("[BASELINE] proper-lockfile: available (session locking)");
      assert.ok(true, "session locking library available");
    } catch {
      console.log("[BASELINE] proper-lockfile: not resolvable (may be bundled)");
      assert.ok(true, "baseline frozen: lockfile check");
    }
  });
});
