import ovh
import os
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Tworzy OVH consumer_key i (opcjonalnie) zapisuje go do ~/.ovh.conf'

    def add_arguments(self, parser):
        parser.add_argument('--app-key', type=str, required=True, help='OVH Application Key')
        parser.add_argument('--app-secret', type=str, required=True, help='OVH Application Secret')
        parser.add_argument('--save', action='store_true', help='Zapisz dane do ~/.ovh.conf')

    def handle(self, *args, **options):
        app_key = options['app_key']
        app_secret = options['app_secret']

        # 🔐 Inicjalizacja klienta OVH
        client = ovh.Client(
            endpoint='ovh-eu',
            application_key=app_key,
            application_secret=app_secret,
        )

        # 📦 Uprawnienia do API
        ck = client.new_consumer_key_request()
        ck.add_recursive_rules(ovh.API_READ_WRITE, '/cdn')
        ck.add_recursive_rules(ovh.API_READ_WRITE, '/cloud')
        ck.add_recursive_rules(ovh.API_READ_WRITE, '/storage')
        ck.add_recursive_rules(ovh.API_READ_WRITE, '/me')
        ck.add_recursive_rules(ovh.API_READ_WRITE, '/domain')

        # 🚀 Żądanie klucza
        validation = ck.request()

        self.stdout.write(self.style.SUCCESS("✅ Skonfigurowano żądanie klucza OVH API"))
        self.stdout.write(f"🔗 Zaloguj się i zatwierdź dostęp:\n{validation['validationUrl']}")
        self.stdout.write(f"\n🗝️  Twój consumer_key (działa po zatwierdzeniu):\n{validation['consumerKey']}")

        if options['save']:
            ovh_conf_path = os.path.expanduser("~/.ovh.conf")
            with open(ovh_conf_path, "w") as f:
                f.write(f"""[default]
                    endpoint=ovh-eu
                    application_key={app_key}
                    application_secret={app_secret}
                    consumer_key={validation['consumerKey']}
                    """)
            self.stdout.write(self.style.SUCCESS(f"💾 Dane zapisane do {ovh_conf_path}"))



# python manage.py generate_consumer_key --app-key=AK_xxx --app-secret=xxx --save
