import * as fs from 'fs';
import * as path from 'path';

/**
 * Updates the backend .env file with deployed contract addresses
 */
async function main() {
  const deploymentPath = path.join(__dirname, '../deployments/deployment.json');

  if (!fs.existsSync(deploymentPath)) {
    console.error('Deployment file not found. Run deploy.ts first.');
    process.exit(1);
  }

  const deployment = JSON.parse(fs.readFileSync(deploymentPath, 'utf8'));
  const backendEnvPath = path.join(__dirname, '../../backend/.env');

  if (!fs.existsSync(backendEnvPath)) {
    console.error('Backend .env file not found at:', backendEnvPath);
    process.exit(1);
  }

  let envContent = fs.readFileSync(backendEnvPath, 'utf8');

  // Contract address mappings
  const envUpdates: Record<string, string> = {
    CONTRACT_ADDRESS_LICENSE_NFT: deployment.contracts.LicenseNFT,
    CONTRACT_ADDRESS_APPROVAL_MANAGER: deployment.contracts.ApprovalManager,
    CONTRACT_ADDRESS_DOCUMENT_CHAIN: deployment.contracts.DocumentChain,
    CONTRACT_ADDRESS_WORKFLOW_REGISTRY: deployment.contracts.WorkflowRegistry,
  };

  // Update or append each variable
  for (const [key, value] of Object.entries(envUpdates)) {
    const regex = new RegExp(`^${key}=.*$`, 'm');

    if (regex.test(envContent)) {
      envContent = envContent.replace(regex, `${key}=${value}`);
      console.log(`Updated ${key}`);
    } else {
      envContent += `\n${key}=${value}`;
      console.log(`Added ${key}`);
    }
  }

  fs.writeFileSync(backendEnvPath, envContent);
  console.log('\nBackend .env file updated successfully!');
  console.log('Updated contract addresses:');

  for (const [key, value] of Object.entries(envUpdates)) {
    console.log(`  ${key}=${value}`);
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
