const test = require('node:test')
const assert = require('node:assert')
const fs = require('fs')
const path = require('path')
const os = require('os')

const { analyzeLibraryDeps, printLibraryDepsHints } = require('../src/lib/library-deps-hint')

function captureLogs(fn) {
  const logs = []
  const oldLog = console.log
  console.log = (...args) => {
    logs.push(args.join(' '))
  }
  try {
    fn()
  } finally {
    console.log = oldLog
  }
  return logs.join('\n')
}

test('cmsDependencies hints consult site bild.json before warning about unset deps file', () => {
  const site = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-hints-bildjson-'))
  fs.writeFileSync(path.join(site, 'package.json'), '{"name":"hint-site"}\n', 'utf8')

  // Project-local config (in addition to ~/.bild.json)
  fs.writeFileSync(
    path.join(site, 'bild.json'),
    JSON.stringify(
      {
        cmsDependenciesFile: 'src/cmsDependencies.ts',
        cmsDependenciesImportAlias: '@/cmsDependencies',
      },
      null,
      2,
    ) + '\n',
    'utf8',
  )

  fs.mkdirSync(path.join(site, 'src'), { recursive: true })
  fs.writeFileSync(
    path.join(site, 'src', 'cmsDependencies.ts'),
    `import * as React from 'react'
export const cmsDependencies = { react: { module: React } }
export default cmsDependencies
`,
    'utf8',
  )

  const component = path.join(site, 'src', 'OnlyAlias.tsx')
  fs.writeFileSync(component, `import { cmsDependencies } from '@/cmsDependencies'\nexport function X() { return null }\n`, 'utf8')

  const analysis = analyzeLibraryDeps(component, {
    // Ensure we don't rely on ~/.bild.json for this test
    config: { sitePath: null, cmsDependenciesFile: null, cmsDependenciesImportAlias: null },
  })
  assert.ok(analysis, 'expected analysis result')
  assert.ok(analysis.depsFilePath, 'expected deps file path to resolve via bild.json + inferred site path')

  const out = captureLogs(() => printLibraryDepsHints(analysis, component))
  assert.ok(!out.includes('deps file path is unset'), `unexpected unset-path warning:\n${out}`)
  assert.ok(!out.includes('No deps file path:'), `unexpected unset-path warning:\n${out}`)
})

