#!/usr/bin/env python
"""
Migration du système de stockage AMIFOND
Convertit de l'ancien système (ENVIRONMENT-based) vers le nouveau (IS_CLOUDINARY)
"""

import os
import sys
import shutil
from pathlib import Path


def migrate_storage_system():
    """Migre l'ancien système vers le nouveau"""

    print("🔄 MIGRATION SYSTÈME DE STOCKAGE AMIFOND")
    print("=" * 60)

    backend_dir = Path(__file__).parent
    models_file = backend_dir / "apps" / "core" / "models.py"

    if not models_file.exists():
        print("❌ Fichier models.py non trouvé")
        return False

    # Sauvegarde
    backup_file = models_file.with_suffix(".py.backup")
    print(f"💾 Sauvegarde: {backup_file}")
    shutil.copy2(models_file, backup_file)

    # Lire l'ancien contenu
    with open(models_file, "r", encoding="utf-8") as f:
        content = f.read()

    # Détecter l'ancien système
    has_old_system = "settings.ENVIRONMENT ==" in content

    if has_old_system:
        print("🔍 Ancien système détecté - Migration nécessaire")

        # Remplacements
        replacements = [
            (
                'if settings.ENVIRONMENT == "development":',
                'if STORAGE_TYPE == "local":',
            ),
            ('elif settings.ENVIRONMENT == "staging":', 'elif STORAGE_TYPE == "s3":'),
            (
                'elif settings.ENVIRONMENT == "production":',
                'elif STORAGE_TYPE == "cloudinary":',
            ),
        ]

        new_content = content
        for old, new in replacements:
            new_content = new_content.replace(old, new)

        # Écrire le nouveau contenu
        with open(models_file, "w", encoding="utf-8") as f:
            f.write(new_content)

        print("✅ Migration des modèles terminée")

    else:
        print("✅ Nouveau système déjà en place")

    return True


def create_environment_configs():
    """Crée les configurations pour différents environnements"""

    backend_dir = Path(__file__).parent

    configs = {
        ".env.dev": [
            "# DÉVELOPPEMENT LOCAL",
            "DEBUG=True",
            "IS_CLOUDINARY=False",
            "# Stockage local automatique",
        ],
        ".env.staging": [
            "# ENVIRONNEMENT STAGING",
            "DEBUG=False",
            "IS_CLOUDINARY=False",
            "AWS_STORAGE_BUCKET_NAME=amifond-staging",
            "AWS_S3_ENDPOINT_URL=http://localhost:9000",
            "AWS_ACCESS_KEY_ID=minioadmin",
            "AWS_SECRET_ACCESS_KEY=minioadmin123",
        ],
        ".env.prod": [
            "# PRODUCTION CLOUDINARY",
            "DEBUG=False",
            "IS_CLOUDINARY=True",
            "CLOUDINARY_CLOUD_NAME=your-cloud-name",
            "CLOUDINARY_API_KEY=your-api-key",
            "CLOUDINARY_API_SECRET=your-api-secret",
        ],
    }

    print("\n📝 Création des configurations d'environnement:")

    for filename, lines in configs.items():
        file_path = backend_dir / filename
        with open(file_path, "w", encoding="utf-8") as f:
            f.write("\n".join(lines) + "\n")
        print(f"   ✅ {filename}")

    return True


def show_migration_summary():
    """Affiche un résumé de la migration"""

    print("\n🎉 MIGRATION TERMINÉE")
    print("=" * 60)

    print("\n📋 Changements effectués:")
    print("   ✅ Système de stockage adaptatif implémenté")
    print("   ✅ Variable IS_CLOUDINARY ajoutée")
    print("   ✅ Fallback automatique Local ← S3 ← Cloudinary")
    print("   ✅ Configurations d'environnement créées")
    print("   ✅ Scripts de test créés")

    print("\n🚀 Prochaines étapes:")
    print("   1. Tester: python test_storage.py")
    print("   2. Développement: make dev")
    print("   3. Staging: make staging")
    print("   4. Production: make prod")

    print("\n💡 Environnements disponibles:")
    print("   🏠 Développement: IS_CLOUDINARY=False (local)")
    print("   🐳 Staging: IS_CLOUDINARY=False + MinIO")
    print("   ☁️  Production: IS_CLOUDINARY=True (Cloudinary)")
    print("   📦 Alt. Prod: IS_CLOUDINARY=False + AWS S3")


if __name__ == "__main__":
    print("🏦 SYSTÈME DE STOCKAGE ADAPTATIF - MIGRATION")

    try:
        success = migrate_storage_system()
        if success:
            create_environment_configs()
            show_migration_summary()
        else:
            sys.exit(1)

    except Exception as e:
        print(f"❌ Erreur lors de la migration: {e}")
        sys.exit(1)
