"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DATA_DIR = void 0;
exports.atomicWriteSync = atomicWriteSync;
exports.initDataDirs = initDataDirs;
exports.getConfig = getConfig;
exports.getAdminUsername = getAdminUsername;
exports.isAdminUser = isAdminUser;
exports.isProjectOwner = isProjectOwner;
exports.getUserWorkspace = getUserWorkspace;
exports.getRegisteredUsers = getRegisteredUsers;
exports.getProjects = getProjects;
exports.saveProjects = saveProjects;
exports.getProject = getProject;
exports.saveProject = saveProject;
exports.deleteProject = deleteProject;
exports.getGlobalShortcuts = getGlobalShortcuts;
exports.saveGlobalShortcuts = saveGlobalShortcuts;
exports.ccwebDir = ccwebDir;
exports.writeProjectConfig = writeProjectConfig;
exports.readProjectConfig = readProjectConfig;
exports.readProjectShortcuts = readProjectShortcuts;
exports.saveProjectShortcuts = saveProjectShortcuts;
exports.updateProjectConfig = updateProjectConfig;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const logger_1 = require("./logger");
const log = (0, logger_1.modLogger)('config');
exports.DATA_DIR = process.env.CCWEB_DATA_DIR || path.join(__dirname, '../../data');
/** Atomic write: write to temp file then rename, preventing corruption on crash */
function atomicWriteSync(filePath, data) {
    const tmpPath = filePath + `.tmp.${process.pid}`;
    fs.writeFileSync(tmpPath, data, 'utf-8');
    fs.renameSync(tmpPath, filePath);
}
const CONFIG_FILE = path.join(exports.DATA_DIR, 'config.json');
const PROJECTS_FILE = path.join(exports.DATA_DIR, 'projects.json');
const SHORTCUTS_FILE = path.join(exports.DATA_DIR, 'global-shortcuts.json');
function initDataDirs() {
    if (!fs.existsSync(exports.DATA_DIR)) {
        fs.mkdirSync(exports.DATA_DIR, { recursive: true });
    }
    if (!fs.existsSync(PROJECTS_FILE)) {
        fs.writeFileSync(PROJECTS_FILE, JSON.stringify([], null, 2), 'utf-8');
    }
}
// Cache getConfig() — config.json rarely changes, avoid repeated disk reads
let _configCache = null;
let _configMtime = 0;
function getConfig() {
    if (!fs.existsSync(CONFIG_FILE)) {
        throw new Error('Config file not found. Please run: npm run setup');
    }
    const mtime = fs.statSync(CONFIG_FILE).mtimeMs;
    if (_configCache && mtime === _configMtime)
        return _configCache;
    const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
    _configCache = JSON.parse(raw);
    _configMtime = mtime;
    return _configCache;
}
function getAdminUsername() {
    try {
        return getConfig().username;
    }
    catch {
        return undefined;
    }
}
function isAdminUser(username) {
    if (!username)
        return false;
    // When config.json doesn't exist (no setup yet), localhost auth uses this sentinel.
    // Treat it as admin so filesystem defaults to ~/Projects instead of ~/Projects__local_admin__.
    if (username === '__local_admin__' && getAdminUsername() === undefined)
        return true;
    return username === getAdminUsername();
}
function isProjectOwner(project, username) {
    if (!username)
        return false;
    if (project.owner)
        return project.owner === username;
    return isAdminUser(username);
}
/** Get the workspace root folder for a user. Admin → ~/Projects, others → ~/Projects{username} */
function getUserWorkspace(username) {
    const home = os.homedir();
    if (!username || isAdminUser(username))
        return path.join(home, 'Projects');
    return path.join(home, `Projects${username}`);
}
const USERS_FILE = path.join(exports.DATA_DIR, 'users.json');
/** Get all registered users (from users.json) */
function getRegisteredUsers() {
    if (!fs.existsSync(USERS_FILE))
        return [];
    try {
        return JSON.parse(fs.readFileSync(USERS_FILE, 'utf-8'));
    }
    catch {
        return [];
    }
}
function getProjects() {
    if (!fs.existsSync(PROJECTS_FILE))
        return [];
    try {
        const raw = fs.readFileSync(PROJECTS_FILE, 'utf-8');
        return JSON.parse(raw);
    }
    catch (err) {
        log.error({ err, file: PROJECTS_FILE }, 'failed to parse projects.json — returning empty list');
        return [];
    }
}
function saveProjects(projects) {
    atomicWriteSync(PROJECTS_FILE, JSON.stringify(projects, null, 2));
}
function getProject(id) {
    return getProjects().find((p) => p.id === id);
}
function saveProject(project) {
    const projects = getProjects();
    const index = projects.findIndex((p) => p.id === project.id);
    if (index >= 0) {
        projects[index] = project;
    }
    else {
        projects.push(project);
    }
    saveProjects(projects);
}
function deleteProject(id) {
    saveProjects(getProjects().filter((p) => p.id !== id));
}
/** Get the shortcuts file path for a given user. Undefined/admin uses the legacy file. */
function shortcutsFileForUser(username) {
    if (!username || isAdminUser(username))
        return SHORTCUTS_FILE;
    const safe = username.replace(/[^a-zA-Z0-9_-]/g, '_');
    return path.join(exports.DATA_DIR, `global-shortcuts-${safe}.json`);
}
function getGlobalShortcuts(username) {
    const file = shortcutsFileForUser(username);
    if (!fs.existsSync(file))
        return [];
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return [];
    }
}
function saveGlobalShortcuts(shortcuts, username) {
    const file = shortcutsFileForUser(username);
    atomicWriteSync(file, JSON.stringify(shortcuts, null, 2));
}
// ── .ccweb/ per-project config ────────────────────────────────────────────────
const CCWEB_DIR = '.ccweb';
const PROJECT_CONFIG_FILE = 'project.json';
function ccwebDir(folderPath) {
    return path.join(folderPath, CCWEB_DIR);
}
/** Write .ccweb/project.json into the project folder */
function writeProjectConfig(folderPath, project) {
    const dir = ccwebDir(folderPath);
    fs.mkdirSync(dir, { recursive: true });
    const config = {
        id: project.id,
        name: project.name,
        permissionMode: project.permissionMode,
        cliTool: project.cliTool,
        createdAt: project.createdAt,
    };
    atomicWriteSync(path.join(dir, PROJECT_CONFIG_FILE), JSON.stringify(config, null, 2));
}
/** Read .ccweb/project.json from a project folder. Returns null if not found. */
function readProjectConfig(folderPath) {
    const file = path.join(ccwebDir(folderPath), PROJECT_CONFIG_FILE);
    if (!fs.existsSync(file))
        return null;
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return null;
    }
}
const PROJECT_SHORTCUTS_FILE = 'shortcuts.json';
function readProjectShortcuts(folderPath) {
    const file = path.join(ccwebDir(folderPath), PROJECT_SHORTCUTS_FILE);
    if (!fs.existsSync(file))
        return [];
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return [];
    }
}
function saveProjectShortcuts(folderPath, shortcuts) {
    const dir = ccwebDir(folderPath);
    fs.mkdirSync(dir, { recursive: true });
    atomicWriteSync(path.join(dir, PROJECT_SHORTCUTS_FILE), JSON.stringify(shortcuts, null, 2));
}
/** Update .ccweb/project.json (partial update) */
function updateProjectConfig(folderPath, updates) {
    const existing = readProjectConfig(folderPath);
    if (!existing)
        return;
    const merged = { ...existing, ...updates };
    const dir = ccwebDir(folderPath);
    atomicWriteSync(path.join(dir, PROJECT_CONFIG_FILE), JSON.stringify(merged, null, 2));
}
//# sourceMappingURL=config.js.map