const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const versionFilePath = path.resolve(__dirname, 'version.json');
const deploysFilePath = path.resolve(__dirname, 'deploys.json');

// 1. Obter informações de commit do Git
let commitHash = 'unknown';
let commitMessage = 'unknown';
let author = 'unknown';

try {
  commitHash = execSync('git rev-parse --short HEAD').toString().trim();
  commitMessage = execSync('git log -1 --pretty=format:"%s"').toString().trim();
  author = execSync('git log -1 --pretty=format:"%an"').toString().trim();
} catch (e) {
  console.error('Falha ao obter detalhes do git:', e.message);
}

// 2. Carregar versão atual ou inicializar
let data = {
  version: 'v1.0.0',
  buildCount: 0,
  lastDeploy: ''
};

if (fs.existsSync(versionFilePath)) {
  try {
    data = JSON.parse(fs.readFileSync(versionFilePath, 'utf8'));
  } catch (e) {
    console.error('Falha ao analisar version.json, reiniciando.');
  }
}

// 3. Incrementar buildCount (+1) e atualizar versão v1.0.x
data.buildCount = (data.buildCount || 0) + 1;
data.version = `v1.0.${data.buildCount}`; // v1.+1
data.lastDeploy = new Date().toISOString();
data.lastCommit = {
  hash: commitHash,
  message: commitMessage,
  author: author
};

// 4. Salvar version.json local
fs.writeFileSync(versionFilePath, JSON.stringify(data, null, 2), 'utf8');

// Copiar para a pasta pública do frontend para que fique exposto via HTTP
const publicVersionPath = path.resolve(__dirname, 'frontend/public/version.json');
fs.mkdirSync(path.dirname(publicVersionPath), { recursive: true });
fs.writeFileSync(publicVersionPath, JSON.stringify(data, null, 2), 'utf8');

// 5. Adicionar entrada de histórico no deploys.json
let deploys = [];
if (fs.existsSync(deploysFilePath)) {
  try {
    deploys = JSON.parse(fs.readFileSync(deploysFilePath, 'utf8'));
  } catch (e) {
    console.error('Falha ao analisar deploys.json');
  }
}

deploys.unshift({
  version: data.version,
  buildCount: data.buildCount,
  timestamp: data.lastDeploy,
  commitHash,
  commitMessage,
  author,
  status: 'Sucesso'
});

// Limitar o histórico de deploys a 30 registros
deploys = deploys.slice(0, 30);

fs.writeFileSync(deploysFilePath, JSON.stringify(deploys, null, 2), 'utf8');

// Copiar deploys.json histórico para a pasta pública do frontend
const publicDeploysPath = path.resolve(__dirname, 'frontend/public/deploys.json');
fs.writeFileSync(publicDeploysPath, JSON.stringify(deploys, null, 2), 'utf8');

console.log(`Versão atualizada para ${data.version} (build #${data.buildCount})`);
