const fs = require('fs');

console.log('🔧 Merging position sections (attempt 2)...');

let content = fs.readFileSync('/app/app/automation-v2/page.js', 'utf8');

// First, remove the separate "Open Positions" section completely
const openPosStart = content.indexOf('          {/* Positions */}');
const openPosEnd = content.indexOf('          )}', openPosStart + 50) + 12; // Get the closing

if (openPosStart > -1 && openPosEnd > openPosStart) {
  const before = content.slice(0, openPosStart);
  const after = content.slice(openPosEnd);
  content = before + after;
  console.log('✅ Removed separate Open Positions section');
} else {
  console.log('❌ Could not find Open Positions section to remove');
}

// Now find and replace the Position Monitor section
const monitorStart = content.indexOf('          {/* Position Monitor */}');
if (monitorStart > -1) {
  const monitorEnd = content.indexOf('          )}', monitorStart + 50) + 12;
  
  if (monitorEnd > monitorStart) {
    const newSection = `          {/* Merged Position Status & Monitor */}
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
            <h3 className="text-lg font-bold text-white mb-4">📊 Position Status & Monitor</h3>
            
            {/* Monitor Status Section */}
            {monitorData && (
              <div className="mb-6 p-4 bg-gray-700/50 rounded-lg border border-gray-600">
                <h4 className="text-md font-semibold text-gray-200 mb-3">📈 Monitor Overview</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex justify-between items-center">
                    <span className="text-gray-400">Has Position:</span>
                    <span className={\`px-2 py-1 rounded text-xs font-semibold \${
                      monitorData.hasPosition ? 'bg-green-600 text-white' : 'bg-gray-600 text-gray-300'
                    }\`}>
                      {monitorData.hasPosition ? '✅ YES' : '❌ NO'}
                    </span>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span className="text-gray-400">Risk Level:</span>
                    <span className={\`px-2 py-1 rounded text-xs font-semibold \${
                      monitorData.riskLevel === 'HIGH' ? 'bg-red-600 text-white' : 
                      monitorData.riskLevel === 'MEDIUM' ? 'bg-yellow-600 text-white' : 
                      'bg-green-600 text-white'
                    }\`}>
                      {monitorData.riskLevel}
                    </span>
                  </div>
                </div>
                
                <div className="mt-3 text-xs text-gray-400">
                  <strong>Next Action:</strong> {monitorData.nextAction}
                </div>

                {monitorData.orphanedOrderCleanup && (
                  <div className={\`mt-3 p-2 rounded-lg \${
                    monitorData.orphanedOrderCleanup.success ? 'bg-green-900 border border-green-600' : 'bg-red-900 border border-red-600'
                  }\`}>
                    <div className="text-xs font-semibold">
                      {monitorData.orphanedOrderCleanup.success ? '✅ Cleanup Success' : '❌ Cleanup Failed'}
                    </div>
                    <div className="text-xs mt-1">
                      {monitorData.orphanedOrderCleanup.message}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Open Positions Section */}
            {positions.length > 0 ? (
              <div>
                <h4 className="text-md font-semibold text-gray-200 mb-3">📈 Active Positions ({positions.length})</h4>
                <div className="space-y-3">
                  {positions.map((position, index) => (
                    <div key={index} className="p-4 bg-gray-700 rounded-lg border border-gray-600">
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-white font-semibold">{position.symbol}</span>
                        <span className={\`px-2 py-1 rounded text-xs font-semibold \${
                          position.side === 'LONG' ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
                        }\`}>
                          {position.side}
                        </span>
                      </div>
                      
                      <div className="grid grid-cols-2 gap-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-400">Size:</span>
                          <span className="text-white">\${position.size}</span>
                        </div>
                        
                        {position.entryPrice && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">Entry:</span>
                            <span className="text-white">\${position.entryPrice}</span>
                          </div>
                        )}
                        
                        {position.markPrice && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">Mark:</span>
                            <span className="text-white">\${position.markPrice}</span>
                          </div>
                        )}
                        
                        {position.pnl !== undefined && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">PnL:</span>
                            <span className={\`font-semibold \${
                              position.pnl >= 0 ? 'text-green-400' : 'text-red-400'
                            }\`}>
                              \${position.pnl >= 0 ? '+' : ''}\${position.pnl}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="text-center py-6">
                <div className="text-gray-500 text-4xl mb-2">📊</div>
                <h4 className="text-gray-400 font-medium">No Active Positions</h4>
                <p className="text-gray-500 text-sm mt-1">Start automation to begin trading</p>
              </div>
            )}
          </div>

`;

    content = content.slice(0, monitorStart) + newSection + content.slice(monitorEnd);
    console.log('✅ Updated Position Monitor with merged content');
  } else {
    console.log('❌ Could not find Position Monitor end');
  }
} else {
  console.log('❌ Could not find Position Monitor section');
}

fs.writeFileSync('/app/app/automation-v2/page.js', content);
console.log('🎉 Positions merged successfully!');
