import * as path from 'node:path';
import * as os from 'node:os';
import { resolveDataDir } from '../../src/comm/data-dir';
import { pUploadPath, pCachePath, pPluginPath, pSqlitePath, pWorkspacePath } from '../../src/comm/path';
import { resolveAgentSessionTreeConfig } from '../../src/modules/netaclaw/session-tree/factory';

describe('resolveDataDir', () => {
  it('prefers validated data.dir from config', () => {
    const configDir = path.join(os.tmpdir(), 'neta-config-data');
    const dir = resolveDataDir({
      isPkg: true,
      execDir: 'C:/Program Files/Neta',
      config: { data: { dir: configDir } },
      cwd: 'C:/Users/demo/Desktop',
    });

    expect(path.normalize(dir)).toBe(path.normalize(configDir));
  });

  it('uses NETA_DATA_DIR as second priority', () => {
    const original = process.env.NETA_DATA_DIR;
    const envDir = path.join(os.tmpdir(), 'neta-env-data');
    process.env.NETA_DATA_DIR = envDir;
    try {
      const dir = resolveDataDir({
        isPkg: true,
        execDir: 'C:/Program Files/Neta',
        cwd: 'C:/Users/demo/Desktop',
      });
      expect(path.normalize(dir)).toBe(path.normalize(envDir));
    } finally {
      if (original === undefined) delete process.env.NETA_DATA_DIR;
      else process.env.NETA_DATA_DIR = original;
    }
  });

  it('falls back to cwd/dist in development mode', () => {
    const dir = resolveDataDir({
      isPkg: false,
      execDir: 'C:/Program Files/Neta',
      cwd: 'C:/Users/demo/project',
    });
    expect(path.normalize(dir)).toBe(path.normalize('C:/Users/demo/project/dist'));
  });
});

describe('installer-aware writable paths', () => {
  let dataDir: string;

  beforeEach(() => {
    dataDir = path.join(os.tmpdir(), `neta-data-dir-test-${Date.now()}-${Math.random().toString(16).slice(2)}`);
    process.env.NETA_DATA_DIR = dataDir;
  });

  afterEach(() => {
    delete process.env.NETA_DATA_DIR;
  });

  it('maps comm/path writable directories to data.dir and creates directory roots', () => {
    expect(path.normalize(pUploadPath())).toBe(path.normalize(path.join(dataDir, 'uploads')));
    expect(path.normalize(pWorkspacePath())).toBe(path.normalize(path.join(dataDir, 'workspace')));
    expect(path.normalize(pCachePath())).toBe(path.normalize(path.join(dataDir, 'cache')));
    expect(path.normalize(pPluginPath())).toBe(path.normalize(path.join(dataDir, 'plugins')));
    expect(path.normalize(pSqlitePath())).toBe(path.normalize(path.join(dataDir, 'cool.sqlite')));
  });

  it('maps session tree root to data.dir/sessions', () => {
    const sessionDataDir = path.join(os.tmpdir(), 'neta-session-data');
    const resolved = resolveAgentSessionTreeConfig(undefined, { backend: 'file', dataDir: sessionDataDir });
    expect(path.normalize(resolved.file!.rootDir)).toBe(path.normalize(path.join(sessionDataDir, 'sessions')));
  });
});
