import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'

/**
 * Temporary file management for tests.
 * Creates real files instead of mocking filesystem.
 */
export class TempFileManager {
  constructor() {
    this.tempDirs = []
  }

  /**
   * Create a temporary directory for test files.
   */
  createTempDir() {
    const tempDir = mkdtempSync(join(tmpdir(), 'mithril-test-'))
    this.tempDirs.push(tempDir)
    return tempDir
  }

  /**
   * Create a test SSH key pair in a temp directory.
   */
  createTestSSHKeys(tempDir) {
    const sshDir = join(tempDir, '.ssh')
    mkdirSync(sshDir, { recursive: true })

    // Test public key (not a real key, safe for testing)
    const publicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTest1234567890abcdefghijklmnopqrstuvwxyz test@mithril'
    const privateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn
TEST-PRIVATE-KEY-CONTENT-NOT-REAL
-----END OPENSSH PRIVATE KEY-----`

    const publicKeyPath = join(sshDir, 'id_rsa.pub')
    const privateKeyPath = join(sshDir, 'id_rsa')

    writeFileSync(publicKeyPath, publicKey)
    writeFileSync(privateKeyPath, privateKey, { mode: 0o600 })

    return { publicKeyPath, privateKeyPath, publicKey }
  }

  /**
   * Create a mock SSH binary for testing SSH command execution.
   */
  createMockSSHBinary(tempDir) {
    const mockSSHPath = join(tempDir, 'ssh')
    
    // Create a simple script that logs arguments
    const mockSSHScript = `#!/usr/bin/env node
console.log('Mock SSH called with:', process.argv.slice(2).join(' '))
console.log('SSH test successful')
process.exit(0)
`
    
    writeFileSync(mockSSHPath, mockSSHScript, { mode: 0o755 })
    return mockSSHPath
  }

  /**
   * Clean up all temporary directories.
   */
  cleanup() {
    this.tempDirs.forEach(dir => {
      try {
        rmSync(dir, { recursive: true, force: true })
      } catch (error) {
        console.warn(`Failed to clean up ${dir}:`, error.message)
      }
    })
    this.tempDirs = []
  }
}

/**
 * Create a new temp file manager for a test suite.
 */
export function createTempFileManager() {
  return new TempFileManager()
}