import os
from datetime import timedelta

from django.apps import AppConfig
from django.conf import settings
from django.db.utils import OperationalError


class MainConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'main'

    def ready(self):
        # Local-development convenience only: seed a test user, sample wallet
        # history, and an admin account when the dev server starts.
        if not settings.DEBUG or os.environ.get('RUN_MAIN') != 'true':
            return

        from django.contrib.auth import get_user_model
        from django.utils import timezone
        from .models import Transaction

        User = get_user_model()
        phone_username = '+33784781469'
        password = '000000'

        try:
            # Approved test user (is_active=True so it can log in immediately).
            user, created = User.objects.get_or_create(
                username=phone_username,
                defaults={'is_active': True},
            )
            if created:
                user.set_password(password)
            if not user.is_active:
                user.is_active = True
            user.save()

            # Seed sample wallet history so Account Details has data to show.
            if not Transaction.objects.filter(user=user).exists():
                now = timezone.now()
                triples = [
                    ('-160.00', '16.00', '0.12'),
                    ('-16.00', '22.00', '0.17'),
                    ('-22.00', '18.00', '0.14'),
                    ('-18.00', '16.00', '0.12'),
                ]
                step = 0
                for principal, ret, comm in triples:
                    for kind, amount in (
                        (Transaction.TICKET_PRINCIPAL, principal),
                        (Transaction.TICKET_PRINCIPAL_RETURN, ret),
                        (Transaction.COMMISSION, comm),
                    ):
                        Transaction.objects.create(
                            user=user,
                            kind=kind,
                            amount=amount,
                            created_at=now - timedelta(seconds=step * 7),
                        )
                        step += 1

            # Dev superuser for testing the admin approval workflow.
            if not User.objects.filter(is_superuser=True).exists():
                User.objects.create_superuser(username='admin', password='admin')
        except OperationalError:
            # Tables not created yet (migrations pending). Skip until migrated.
            pass
