
# Je vais recréer les fichiers essentiels et créer un ZIP pour faciliter le téléchargement
import os
import zipfile
from datetime import datetime

# Créer un dossier temporaire
if not os.path.exists('groupe-cmi-square'):
    os.makedirs('groupe-cmi-square')

print("📦 Création des fichiers pour Le Groupe CMI...\n")

# 1. backend-server.js
backend_code = """// backend-server.js
// Serveur Node.js pour traiter les paiements Square - Le Groupe CMI

require('dotenv').config();
const express = require('express');
const { Client, Environment } = require('square');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(express.static('public'));

// Configuration Square
const squareClient = new Client({
    accessToken: process.env.SQUARE_ACCESS_TOKEN,
    environment: Environment.Sandbox
});

const PORT = process.env.PORT || 3000;
const LOCATION_ID = process.env.SQUARE_LOCATION_ID;

console.log('\\n' + '='.repeat(70));
console.log('🚀 SERVEUR SQUARE - LE GROUPE CMI');
console.log('='.repeat(70));
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('Square Mode:', process.env.SQUARE_ENVIRONMENT || 'sandbox');
console.log('Port:', PORT);
console.log('Location ID:', LOCATION_ID);
console.log('='.repeat(70) + '\\n');

// Route principale
app.get('/', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Groupe CMI - Paiements Square</title>
            <style>
                body { font-family: Arial; max-width: 600px; margin: 50px auto; padding: 20px; }
                .status { padding: 20px; background: #e8f5e9; border-radius: 5px; }
                h1 { color: #1976d2; }
            </style>
        </head>
        <body>
            <h1>✅ Serveur Square - Le Groupe CMI</h1>
            <div class="status">
                <p>✅ Serveur en ligne et fonctionnel</p>
                <p>📍 Location ID: ${LOCATION_ID}</p>
                <p>🔧 Mode: Sandbox</p>
                <h3>Endpoints disponibles:</h3>
                <ul>
                    <li>POST /api/process-payment - Traiter un paiement</li>
                    <li>POST /api/webhooks/square - Recevoir les webhooks Square</li>
                    <li>GET /api/payment/:id - Vérifier un paiement</li>
                </ul>
            </div>
        </body>
        </html>
    `);
});

// Route: Traiter un paiement
app.post('/api/process-payment', async (req, res) => {
    const { sourceId, amount, urgency, customerInfo, projectInfo, question } = req.body;
    
    if (!sourceId || !amount) {
        return res.status(400).json({ success: false, error: 'Données manquantes' });
    }
    
    try {
        const subtotal = amount;
        const tps = Math.round(subtotal * 0.05);
        const tvq = Math.round(subtotal * 0.09975);
        const totalAmount = subtotal + tps + tvq;
        
        const { result } = await squareClient.paymentsApi.createPayment({
            sourceId: sourceId,
            amountMoney: {
                amount: BigInt(totalAmount),
                currency: 'CAD'
            },
            locationId: LOCATION_ID,
            idempotencyKey: crypto.randomUUID(),
            note: `Consultation ${urgency} - ${customerInfo.nom} ${customerInfo.prenom}`,
            buyerEmailAddress: customerInfo.email,
            referenceId: `CMI-${Date.now()}`
        });
        
        console.log('✅ Paiement créé:', result.payment.id);
        
        res.json({
            success: true,
            payment: {
                id: result.payment.id,
                status: result.payment.status,
                receiptUrl: result.payment.receiptUrl,
                amount: totalAmount / 100
            }
        });
        
    } catch (error) {
        console.error('❌ Erreur paiement:', error);
        res.status(500).json({
            success: false,
            error: 'Paiement non traité',
            details: error.message
        });
    }
});

// Route: Webhooks Square
app.post('/api/webhooks/square', async (req, res) => {
    const signature = req.headers['x-square-hmacsha256-signature'];
    const webhookSignatureKey = process.env.SQUARE_WEBHOOK_SIGNATURE_KEY;
    
    if (webhookSignatureKey && webhookSignatureKey !== 'VOTRE_SIGNATURE_KEY_ICI') {
        const body = JSON.stringify(req.body);
        const hmac = crypto.createHmac('sha256', webhookSignatureKey);
        hmac.update(body);
        const expectedSignature = hmac.digest('base64');
        
        if (signature !== expectedSignature) {
            console.error('❌ Signature webhook invalide');
            return res.status(401).json({ error: 'Signature invalide' });
        }
    }
    
    const event = req.body;
    console.log('📨 Webhook reçu:', event.type);
    
    res.status(200).json({ received: true });
});

// Route: Vérifier un paiement
app.get('/api/payment/:paymentId', async (req, res) => {
    try {
        const { result } = await squareClient.paymentsApi.getPayment(req.params.paymentId);
        res.json({ success: true, payment: result.payment });
    } catch (error) {
        res.status(404).json({ success: false, error: 'Paiement introuvable' });
    }
});

// Démarrer le serveur
app.listen(PORT, () => {
    console.log(`✅ Serveur démarré sur http://localhost:${PORT}`);
    console.log(`📝 Prêt à recevoir des paiements\\n`);
});
"""

with open('groupe-cmi-square/backend-server.js', 'w', encoding='utf-8') as f:
    f.write(backend_code)
print("✅ backend-server.js créé")

# 2. .env
env_content = """# Configuration Square - Le Groupe CMI Experts-Conseils

SQUARE_ACCESS_TOKEN=EAAAlyRwxD0nTIiwDdlR6ksbq0cr-nAcTCE1XygjMrawBRNloWDxIpuJHMg2SW4X
SQUARE_APPLICATION_ID=sq0idp-sEX-Cpu6m_LugzqOXB1O0w
SQUARE_LOCATION_ID=LA3GJXPQDQEWA
SQUARE_ENVIRONMENT=sandbox
SQUARE_WEBHOOK_SIGNATURE_KEY=VOTRE_SIGNATURE_KEY_ICI

PORT=3000
NODE_ENV=development
APP_URL=http://localhost:3000
"""

with open('groupe-cmi-square/.env', 'w', encoding='utf-8') as f:
    f.write(env_content)
print("✅ .env créé")

# 3. package.json
package_json = """{
  "name": "groupe-cmi-square-integration",
  "version": "1.0.0",
  "description": "Intégration Square pour Le Groupe CMI",
  "main": "backend-server.js",
  "scripts": {
    "start": "node backend-server.js",
    "dev": "nodemon backend-server.js",
    "test": "node test-connection.js"
  },
  "author": "Le Groupe CMI Experts-Conseils",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "square": "^35.0.0",
    "dotenv": "^16.3.1",
    "body-parser": "^1.20.2",
    "cors": "^2.8.5"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"
  }
}
"""

with open('groupe-cmi-square/package.json', 'w', encoding='utf-8') as f:
    f.write(package_json)
print("✅ package.json créé")

# 4. test-connection.js
test_script = """// test-connection.js
require('dotenv').config();
const { Client, Environment } = require('square');

console.log('\\n' + '='.repeat(70));
console.log('TEST DE CONNEXION SQUARE');
console.log('='.repeat(70) + '\\n');

console.log('Configuration:');
console.log('  ACCESS_TOKEN:', process.env.SQUARE_ACCESS_TOKEN ? '✅' : '❌');
console.log('  APPLICATION_ID:', process.env.SQUARE_APPLICATION_ID ? '✅' : '❌');
console.log('  LOCATION_ID:', process.env.SQUARE_LOCATION_ID ? '✅' : '❌');
console.log('');

const client = new Client({
    accessToken: process.env.SQUARE_ACCESS_TOKEN,
    environment: Environment.Sandbox
});

async function test() {
    try {
        const { result } = await client.locationsApi.retrieveLocation(
            process.env.SQUARE_LOCATION_ID
        );
        
        console.log('✅ CONNEXION RÉUSSIE!\\n');
        console.log('Location:', result.location.name || result.location.id);
        console.log('Status:', result.location.status);
        console.log('\\n' + '='.repeat(70));
        console.log('✅ Configuration correcte! Vous pouvez démarrer le serveur.');
        console.log('='.repeat(70) + '\\n');
    } catch (error) {
        console.log('❌ ERREUR:', error.message + '\\n');
    }
}

test();
"""

with open('groupe-cmi-square/test-connection.js', 'w', encoding='utf-8') as f:
    f.write(test_script)
print("✅ test-connection.js créé")

# 5. README simple
readme = """# Installation Square - Groupe CMI

## Commandes rapides:

1. npm install
2. npm test
3. npm run dev

Votre serveur démarrera sur: http://localhost:3000

Pour les webhooks, utilisez ngrok:
- Terminal 1: npm run dev
- Terminal 2: ngrok http 3000
"""

with open('groupe-cmi-square/README.md', 'w', encoding='utf-8') as f:
    f.write(readme)
print("✅ README.md créé")

# Créer un ZIP
print("\n📦 Création du fichier ZIP...")
with zipfile.ZipFile('groupe-cmi-square.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, dirs, files in os.walk('groupe-cmi-square'):
        for file in files:
            file_path = os.path.join(root, file)
            arcname = os.path.relpath(file_path, 'groupe-cmi-square')
            zipf.write(file_path, arcname)

print("✅ groupe-cmi-square.zip créé")

print("\n" + "="*70)
print("✅ TOUS LES FICHIERS SONT PRÊTS!")
print("="*70)
print("\nVous pouvez télécharger:")
print("1. groupe-cmi-square.zip (contient tout)")
print("OU les fichiers individuels ci-dessus")
print("\n" + "="*70)
