import { homedir, platform } from 'node:os';
import { join } from 'node:path';
import { existsSync, mkdirSync, renameSync, readdirSync } from 'node:fs';
import { config } from '../config.js';
/**
 * Resolve the platform-native data directory for Al Moasis · المؤسس.
 *
 * macOS:   ~/Library/Application Support/AlMoasis
 * Windows: %APPDATA%\AlMoasis (e.g. C:\Users\X\AppData\Roaming\AlMoasis)
 * Linux:   $XDG_DATA_HOME/almoasis or ~/.local/share/almoasis
 *
 * Override via MUASSIS_DATA_DIR (legacy) or ALMOASIS_DATA_DIR env var.
 *
 * One-time auto-migration: if a legacy `Muassis` data dir exists alongside
 * an empty new `AlMoasis` dir, the legacy contents are moved into the new
 * location. This keeps brand-rename installs from losing tenants, WA
 * sessions, and SQLite state.
 */
function resolveDataDirPaths() {
    const home = homedir();
    switch (platform()) {
        case 'darwin':
            return {
                current: join(home, 'Library', 'Application Support', 'AlMoasis'),
                legacy: join(home, 'Library', 'Application Support', 'Muassis'),
            };
        case 'win32': {
            const appData = process.env.APPDATA ?? join(home, 'AppData', 'Roaming');
            return {
                current: join(appData, 'AlMoasis'),
                legacy: join(appData, 'Muassis'),
            };
        }
        default: {
            const xdg = process.env.XDG_DATA_HOME ?? join(home, '.local', 'share');
            return {
                current: join(xdg, 'almoasis'),
                legacy: join(xdg, 'muassis'),
            };
        }
    }
}
let migrationChecked = false;
function ensureLegacyMigrated(currentDir, legacyDir) {
    if (migrationChecked)
        return;
    migrationChecked = true;
    if (!existsSync(legacyDir))
        return;
    if (existsSync(currentDir)) {
        try {
            const entries = readdirSync(currentDir);
            if (entries.length > 0)
                return; // new dir is already populated — don't clobber
        }
        catch {
            return;
        }
    }
    // Move legacy → current. Use rename for atomicity; falls back to per-entry
    // copy is intentionally not implemented — if rename fails (cross-device),
    // we leave the legacy dir alone and the user can MUASSIS_DATA_DIR-override
    // until they manually move it.
    try {
        renameSync(legacyDir, currentDir);
        process.stderr.write(`[Al Moasis] Migrated legacy data dir: ${legacyDir} → ${currentDir}\n`);
    }
    catch (err) {
        process.stderr.write(`[Al Moasis] Legacy data dir found at ${legacyDir} but auto-migrate failed: ${err.message}. Set ALMOASIS_DATA_DIR or move the directory manually.\n`);
    }
}
export function getDataDir() {
    const override = process.env.ALMOASIS_DATA_DIR || config.MUASSIS_DATA_DIR;
    if (override) {
        mkdirSync(override, { recursive: true });
        return override;
    }
    const { current, legacy } = resolveDataDirPaths();
    ensureLegacyMigrated(current, legacy);
    mkdirSync(current, { recursive: true });
    return current;
}
/** Path to the device-mode SQLite database file. */
export function getSqlitePath() {
    return join(getDataDir(), 'muassis.db');
}
/** Path to the device-mode log file. */
export function getLogPath() {
    return join(getDataDir(), 'muassis.log');
}
/**
 * Root directory for tenant workspaces. Each tenant's files (SOUL.md,
 * BUSINESS.md, KNOWLEDGE/, etc.) live under <root>/<tenantId>/.
 *
 * Override via ALMOASIS_WORKSPACE_ROOT or MUASSIS_WORKSPACE_ROOT (legacy)
 * to share workspaces across multiple gateway instances. Defaults to
 * <dataDir>/workspaces.
 */
export function getWorkspacesRoot() {
    const override = process.env.ALMOASIS_WORKSPACE_ROOT || process.env.MUASSIS_WORKSPACE_ROOT;
    if (override) {
        mkdirSync(override, { recursive: true });
        return override;
    }
    const dir = join(getDataDir(), 'workspaces');
    mkdirSync(dir, { recursive: true });
    return dir;
}
//# sourceMappingURL=data-dir.js.map