#!/usr/bin/env node
const { execSync } = require('child_process')
const path = require('path')

// Get project root (two levels up from this script)
const projectRoot = path.resolve(__dirname, '../..')

// Change to project root
process.chdir(projectRoot)

// Configuration: main branch name (leave empty to auto-detect)
const CONFIG_BRANCH = 'master'

// Detect main branch
let mainBranch = CONFIG_BRANCH

if (!CONFIG_BRANCH) {
  // Auto-detect main branch (priority: master > main > current branch)
  try {
    execSync('git show-ref --verify --quiet refs/heads/master', { stdio: 'ignore' })
    mainBranch = 'master'
  } catch (e) {
    try {
      execSync('git show-ref --verify --quiet refs/heads/main', { stdio: 'ignore' })
      mainBranch = 'main'
    } catch (e2) {
      // Use current branch
      mainBranch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim()
    }
  }
}

// Show files to be pushed
console.log('')
console.log('Files to be pushed:')
console.log('========================================')
try {
  const diffOutput = execSync(`git diff --name-status origin/${mainBranch}..HEAD`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] })
  console.log(diffOutput.trim())
} catch (e) {
  // If remote branch doesn't exist, show all files
  try {
    const logOutput = execSync('git log --name-status --oneline HEAD', { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] })
    const lines = logOutput.split('\n').filter(line => line.trim() && !/^[a-f0-9]/.test(line))
    console.log(lines.join('\n'))
  } catch (e2) {
    // Ignore errors
  }
}
console.log('========================================')
console.log('')

// Push to main branch
console.log('')
console.log(`Pushing to origin/${mainBranch}...`)
console.log('========================================')
try {
  const pushOutput = execSync(`git push origin ${mainBranch}`, { encoding: 'utf-8', stdio: 'inherit' })
  console.log('========================================')
  console.log('')
  console.log('========================================')
  console.log('[OK] Push successful')
  console.log('========================================')
  console.log('')
  process.exit(0)
} catch (error) {
  console.log('========================================')
  console.log('')
  console.log('========================================')
  console.log(`[ERROR] Push failed (exit code: ${error.status || 1})`)
  console.log('========================================')
  console.log('')
  console.log('Please check the error messages above.')
  console.log('')
  process.exit(error.status || 1)
}
