import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { detectProject } from '../src/device/project';

function tempDir(): string {
  return fs.mkdtempSync(path.join(os.tmpdir(), 'agent-project-test-'));
}

test('detects project name from package.json', () => {
  const dir = tempDir();
  fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'buzyteam-web' }));

  const result = detectProject(dir);

  assert.equal(result.name, 'buzyteam-web');
  assert.equal(result.detectionSource, 'package_json');
});

test('detects project name from composer.json when no package.json exists', () => {
  const dir = tempDir();
  fs.writeFileSync(path.join(dir, 'composer.json'), JSON.stringify({ name: 'acme/api' }));

  const result = detectProject(dir);

  assert.equal(result.name, 'acme/api');
  assert.equal(result.detectionSource, 'composer_json');
});

test('falls back to the directory name when no markers are present', () => {
  const dir = tempDir();

  const result = detectProject(dir);

  assert.equal(result.name, path.basename(dir));
  assert.equal(result.detectionSource, 'directory');
});

test('the same path always hashes to the same value, and never leaks the raw path', () => {
  const dir = tempDir();

  const first = detectProject(dir);
  const second = detectProject(dir);

  assert.equal(first.pathHash, second.pathHash);
  assert.equal(first.pathHash.length, 64); // sha256 hex
  assert.doesNotMatch(first.pathHash, new RegExp(dir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
});

test('detects the project root from a nested subdirectory', () => {
  const dir = tempDir();
  fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'nested-project' }));
  const nested = path.join(dir, 'src', 'components');
  fs.mkdirSync(nested, { recursive: true });

  const result = detectProject(nested);

  assert.equal(result.name, 'nested-project');
});
