import { existsSync, mkdirSync, readFileSync } from 'node:fs';
import process__default from 'node:process';
import a from './index5.mjs';
import { CCJK_CONFIG_DIR, SETTINGS_FILE, CLAVUE_DIR } from './constants.mjs';
import { STATUS } from './banner.mjs';
import { writeFileAtomic } from './fs-operations.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:os';
import './index2.mjs';
import 'node:url';
import '../shared/ccjk.gDEDGD_t.mjs';
import 'node:crypto';
import 'node:fs/promises';

const PERMISSION_CONFIG_FILE = join(CCJK_CONFIG_DIR, "permissions.json");
function stringArray(value) {
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function permissionArray(value) {
  return stringArray(value).filter(
    (item) => [
      "file-read",
      "file-write",
      "file-delete",
      "git-operations",
      "npm-commands",
      "node-execution",
      "system-commands",
      "network-access",
      "mcp-server"
    ].includes(item)
  );
}
function mapClaudeRuleToPermission(rule) {
  const normalized = rule.toLowerCase();
  if (normalized.startsWith("read(")) {
    return "file-read";
  }
  if (normalized.startsWith("edit(") || normalized.startsWith("write(") || normalized.startsWith("notebookedit(")) {
    return "file-write";
  }
  if (normalized.startsWith("bash(")) {
    if (/\b(git|gh)\b/.test(normalized)) {
      return "git-operations";
    }
    if (/\b(npm|pnpm|yarn|bun)\b/.test(normalized)) {
      return "npm-commands";
    }
    if (/\b(node|tsx|ts-node)\b/.test(normalized)) {
      return "node-execution";
    }
    if (/\b(curl|wget|scp|ssh)\b/.test(normalized)) {
      return "network-access";
    }
    if (/\b(rm|trash|unlink|rmdir|mv)\b/.test(normalized)) {
      return "file-delete";
    }
    return "system-commands";
  }
  if (normalized.startsWith("webfetch(") || normalized.startsWith("websearch(")) {
    return "network-access";
  }
  if (normalized.startsWith("mcp__")) {
    return "mcp-server";
  }
  return null;
}
function mapClaudeRulesToPermissions(rules) {
  return [...new Set(rules.map(mapClaudeRuleToPermission).filter((item) => Boolean(item)))];
}
function sortedArray(items) {
  return [...items].sort();
}
function normalizePermissions(input) {
  const obj = input && typeof input === "object" && !Array.isArray(input) ? input : {};
  return {
    allowed: [
      ...permissionArray(obj.allowed),
      ...mapClaudeRulesToPermissions(stringArray(obj.allow))
    ].filter((item, index, array) => array.indexOf(item) === index),
    denied: [
      ...permissionArray(obj.denied),
      ...mapClaudeRulesToPermissions(stringArray(obj.deny))
    ].filter((item, index, array) => array.indexOf(item) === index),
    trustedDirectories: [
      ...stringArray(obj.trustedDirectories),
      ...stringArray(obj.additionalDirectories)
    ].filter((item, index, array) => array.indexOf(item) === index),
    autoApprovePatterns: stringArray(obj.autoApprovePatterns)
  };
}
function getClavueSettingsFile() {
  return join(process__default.env.CLAVUE_CONFIG_DIR || CLAVUE_DIR, "settings.json");
}
function shouldPreferClavueSettings() {
  return Boolean(
    process__default.env.CLAVUE_CONFIG_DIR || process__default.env.CLAVUE_DISABLE_LEGACY_CLAUDE_CONFIG || process__default.env.CLAVUE_DISABLE_LEGACY_CLAUDE_COMMANDS || existsSync(getClavueSettingsFile())
  );
}
function readJsonFile(path) {
  try {
    return JSON.parse(readFileSync(path, "utf-8"));
  } catch {
    return null;
  }
}
function getPermissionFallbackFiles() {
  const clavueSettingsFile = getClavueSettingsFile();
  const orderedFiles = shouldPreferClavueSettings() ? [clavueSettingsFile, SETTINGS_FILE] : [SETTINGS_FILE, clavueSettingsFile];
  return [...new Set(orderedFiles)];
}
const PERMISSION_TEMPLATES = [
  {
    id: "development",
    name: "Development",
    description: "Standard development permissions - file read/write, git, npm, node execution",
    permissions: {
      allowed: ["file-read", "file-write", "git-operations", "npm-commands", "node-execution", "mcp-server"],
      denied: ["system-commands", "network-access", "file-delete"],
      trustedDirectories: [],
      autoApprovePatterns: ["*.ts", "*.js", "*.json", "*.md", "*.css", "*.html"]
    }
  },
  {
    id: "readonly",
    name: "Read Only",
    description: "Read-only access - no file modifications or command execution",
    permissions: {
      allowed: ["file-read"],
      denied: ["file-write", "file-delete", "git-operations", "npm-commands", "node-execution", "system-commands", "network-access"],
      trustedDirectories: [],
      autoApprovePatterns: []
    }
  },
  {
    id: "full-trust",
    name: "Full Trust",
    description: "All operations pre-authorized - use with caution",
    permissions: {
      allowed: ["file-read", "file-write", "file-delete", "git-operations", "npm-commands", "node-execution", "system-commands", "network-access", "mcp-server"],
      denied: [],
      trustedDirectories: [],
      autoApprovePatterns: ["*"]
    }
  },
  {
    id: "restricted",
    name: "Restricted",
    description: "Minimal permissions - all operations require confirmation",
    permissions: {
      allowed: [],
      denied: ["file-read", "file-write", "file-delete", "git-operations", "npm-commands", "node-execution", "system-commands", "network-access"],
      trustedDirectories: [],
      autoApprovePatterns: []
    }
  }
];
function readPermissions() {
  if (existsSync(PERMISSION_CONFIG_FILE)) {
    const permissions = readJsonFile(PERMISSION_CONFIG_FILE);
    if (permissions) {
      return normalizePermissions(permissions);
    }
  }
  for (const settingsFile of getPermissionFallbackFiles()) {
    if (existsSync(settingsFile)) {
      const settings = readJsonFile(settingsFile);
      if (settings?.permissions) {
        return normalizePermissions(settings.permissions);
      }
    }
  }
  return PERMISSION_TEMPLATES.find((t) => t.id === "development").permissions;
}
function writePermissions(permissions) {
  try {
    const normalizedPermissions = normalizePermissions(permissions);
    if (!existsSync(CCJK_CONFIG_DIR)) {
      mkdirSync(CCJK_CONFIG_DIR, { recursive: true });
    }
    writeFileAtomic(PERMISSION_CONFIG_FILE, JSON.stringify(normalizedPermissions, null, 2));
    return true;
  } catch {
    return false;
  }
}
function repairPermissions(trustedDirectory = process__default.cwd()) {
  const template = PERMISSION_TEMPLATES.find((t) => t.id === "development");
  const permissions = normalizePermissions(template.permissions);
  if (trustedDirectory && !permissions.trustedDirectories.includes(trustedDirectory)) {
    permissions.trustedDirectories.push(trustedDirectory);
  }
  return writePermissions(permissions);
}
function getCurrentTemplateId() {
  const permissions = readPermissions();
  for (const template of PERMISSION_TEMPLATES) {
    if (JSON.stringify(sortedArray(permissions.allowed)) === JSON.stringify(sortedArray(template.permissions.allowed)) && JSON.stringify(sortedArray(permissions.denied)) === JSON.stringify(sortedArray(template.permissions.denied))) {
      return template.id;
    }
  }
  return null;
}
function displayPermissions() {
  const permissions = readPermissions();
  const templateId = getCurrentTemplateId();
  console.log(a.green("\n\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Claude Code Permissions \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n"));
  console.log(a.white.bold("Trusted Directories:"));
  if (permissions.trustedDirectories.length === 0) {
    console.log(a.gray("  (none)"));
  } else {
    for (const dir of permissions.trustedDirectories) {
      console.log(STATUS.success(dir));
    }
  }
  console.log("");
  console.log(a.white.bold("Pre-authorized Operations:"));
  const allPermissions = [
    "file-read",
    "file-write",
    "file-delete",
    "git-operations",
    "npm-commands",
    "node-execution",
    "system-commands",
    "network-access",
    "mcp-server"
  ];
  for (const perm of allPermissions) {
    const label = perm.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
    if (permissions.allowed.includes(perm)) {
      console.log(STATUS.success(label));
    } else if (permissions.denied.includes(perm)) {
      console.log(STATUS.error(`${label} (denied)`));
    } else {
      console.log(STATUS.warning(`${label} (requires confirmation)`));
    }
  }
  console.log("");
  if (templateId) {
    const template = PERMISSION_TEMPLATES.find((t) => t.id === templateId);
    console.log(a.gray(`Template: ${a.green(template?.name || templateId)}`));
  } else {
    console.log(a.gray("Template: custom"));
  }
  console.log("");
}

export { PERMISSION_TEMPLATES, displayPermissions, getCurrentTemplateId, normalizePermissions, readPermissions, repairPermissions, writePermissions };
