"use strict";

/**
 * openclaw workspace init | validate
 *
 * Manages the OpenClaw workspace at /var/lib/openclaw/.
 */

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

const CONFIG_FILE = "/etc/openclaw/config.json";

function getWorkspaceRoot() {
  if (fs.existsSync(CONFIG_FILE)) {
    const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
    return config.workspace?.root || "/var/lib/openclaw";
  }
  return "/var/lib/openclaw";
}

function init(args) {
  const root = getWorkspaceRoot();
  console.log(`Initializing OpenClaw workspace at ${root}...`);

  const dirs = [
    root,
    path.join(root, "models"),
    path.join(root, "data"),
    path.join(root, "cache"),
    path.join(root, "tmp"),
    path.join(root, "plugins"),
  ];

  for (const dir of dirs) {
    fs.mkdirSync(dir, { recursive: true });
    console.log(`  Created ${dir}`);
  }

  // Write workspace metadata
  const meta = {
    createdAt: new Date().toISOString(),
    version: "1.0.0",
    root: root,
  };
  fs.writeFileSync(
    path.join(root, ".workspace.json"),
    JSON.stringify(meta, null, 2) + "\n"
  );
  console.log(`  Written ${path.join(root, ".workspace.json")}`);

  // Create log directory
  const logDir = "/var/log/openclaw";
  fs.mkdirSync(logDir, { recursive: true });
  console.log(`  Created ${logDir}`);

  console.log("Workspace initialized successfully.");
}

function validate(args) {
  const root = getWorkspaceRoot();
  console.log(`Validating OpenClaw workspace at ${root}...`);

  let valid = true;

  // Check root exists
  if (!fs.existsSync(root)) {
    console.error(`  FAIL: Workspace root not found: ${root}`);
    valid = false;
  } else {
    console.log(`  Root: OK (${root})`);
  }

  // Check subdirectories
  const requiredDirs = ["models", "data", "cache", "tmp"];
  for (const dir of requiredDirs) {
    const fullPath = path.join(root, dir);
    if (!fs.existsSync(fullPath)) {
      console.error(`  FAIL: Missing directory: ${fullPath}`);
      valid = false;
    } else {
      console.log(`  ${dir}/: OK`);
    }
  }

  // Check metadata
  const metaFile = path.join(root, ".workspace.json");
  if (!fs.existsSync(metaFile)) {
    console.error(`  FAIL: Missing workspace metadata: ${metaFile}`);
    valid = false;
  } else {
    console.log("  .workspace.json: OK");
  }

  // Check log directory
  const logDir = "/var/log/openclaw";
  if (!fs.existsSync(logDir)) {
    console.error(`  FAIL: Log directory not found: ${logDir}`);
    valid = false;
  } else {
    console.log(`  Log directory: OK (${logDir})`);
  }

  if (valid) {
    console.log("Workspace is valid.");
  } else {
    console.error("Workspace validation failed.");
    process.exit(1);
  }
}

function run(args) {
  const sub = args[0];

  switch (sub) {
    case "init":
      return init(args.slice(1));
    case "validate":
      return validate(args.slice(1));
    default:
      console.error(`Unknown workspace subcommand: ${sub}`);
      console.error("Usage: openclaw workspace <init|validate>");
      process.exit(1);
  }
}

module.exports = { run };
