import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

export function loadConfig() {
  const configDir = process.env.HER_AGENT_CONFIG_DIR || path.join(os.homedir(), ".her-desktop-agent");
  const configPath = path.join(configDir, "config.json");

  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });

  if (fs.existsSync(configPath)) {
    const parsed = JSON.parse(fs.readFileSync(configPath, "utf8"));
    return {
      token: process.env.HER_AGENT_TOKEN || parsed.token,
      configPath,
      created: false,
    };
  }

  const token = process.env.HER_AGENT_TOKEN || crypto.randomBytes(24).toString("base64url");
  fs.writeFileSync(configPath, JSON.stringify({ token }, null, 2), { mode: 0o600 });

  return {
    token,
    configPath,
    created: true,
  };
}
