#!/usr/bin/env python
"""
Django management command to help manage discounts programmatically.

Usage:
    python manage.py discount_manager --action=create
    python manage.py discount_manager --action=expire
    python manage.py discount_manager --action=report
"""

from decimal import Decimal
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from shop.models import Discount, Product, Category, Order


class Command(BaseCommand):
    help = 'Manage discounts: create, expire, generate reports'

    def add_arguments(self, parser):
        parser.add_argument(
            '--action',
            type=str,
            default='report',
            help='Action to perform: create, expire, report, cleanup'
        )
        parser.add_argument(
            '--name',
            type=str,
            help='Discount name'
        )
        parser.add_argument(
            '--code',
            type=str,
            help='Discount code'
        )
        parser.add_argument(
            '--type',
            type=str,
            choices=['percentage', 'fixed'],
            help='Discount type'
        )
        parser.add_argument(
            '--value',
            type=float,
            help='Discount value'
        )

    def handle(self, *args, **options):
        action = options['action']

        if action == 'create':
            self.create_discount(options)
        elif action == 'expire':
            self.expire_discounts()
        elif action == 'report':
            self.report_discounts()
        elif action == 'cleanup':
            self.cleanup_discounts()
        else:
            self.stdout.write(self.style.ERROR(f'Unknown action: {action}'))

    def create_discount(self, options):
        """Create a new discount via command line"""
        if not options['name'] or not options['type'] or options['value'] is None:
            self.stdout.write(self.style.ERROR(
                'Missing required options: --name, --type, --value'
            ))
            return

        now = timezone.now()
        discount = Discount.objects.create(
            name=options['name'],
            code=options['code'] or None,
            discount_type=options['type'],
            discount_value=Decimal(str(options['value'])),
            start_date=now,
            end_date=now + timedelta(days=30),
            is_active=True
        )

        self.stdout.write(self.style.SUCCESS(
            f'✓ Discount "{discount.name}" created successfully!'
        ))
        self.stdout.write(f'  ID: {discount.id}')
        self.stdout.write(f'  Code: {discount.code or "None (auto-apply)"}')

    def expire_discounts(self):
        """Automatically expire past discounts"""
        now = timezone.now()
        expired = Discount.objects.filter(
            is_active=True,
            end_date__lt=now
        ).update(is_active=False)

        if expired > 0:
            self.stdout.write(self.style.SUCCESS(
                f'✓ Expired {expired} discount(s)'
            ))
        else:
            self.stdout.write('No discounts to expire.')

    def report_discounts(self):
        """Display discount statistics"""
        total = Discount.objects.count()
        active = Discount.objects.filter(
            is_active=True,
            start_date__lte=timezone.now(),
            end_date__gte=timezone.now()
        ).count()
        with_codes = Discount.objects.filter(code__isnull=False).count()

        self.stdout.write(self.style.SUCCESS('\n=== DISCOUNT REPORT ===\n'))
        self.stdout.write(f'Total Discounts: {total}')
        self.stdout.write(f'Currently Active: {active}')
        self.stdout.write(f'With Promo Codes: {with_codes}')

        self.stdout.write(self.style.SUCCESS('\n=== ACTIVE DISCOUNTS ===\n'))

        discounts = Discount.objects.filter(is_active=True).order_by('-created_at')
        if not discounts:
            self.stdout.write('No active discounts.')
            return

        for d in discounts:
            status = '✓ Valid' if d.is_valid() else '⚠ Invalid'
            symbol = '%' if d.discount_type == 'percentage' else '$'
            usage = f'{d.usage_count}/{d.usage_limit}' if d.usage_limit else f'{d.usage_count}/∞'

            self.stdout.write(f'\n[{d.id}] {d.name}')
            self.stdout.write(f'    Status: {status}')
            self.stdout.write(f'    Value: {d.discount_value}{symbol}')
            self.stdout.write(f'    Code: {d.code or "None"}')
            self.stdout.write(f'    Usage: {usage}')
            self.stdout.write(f'    Valid: {d.start_date.date()} to {d.end_date.date()}')

    def cleanup_discounts(self):
        """Archive old expired discounts"""
        cutoff = timezone.now() - timedelta(days=90)
        old = Discount.objects.filter(
            is_active=False,
            end_date__lt=cutoff
        ).count()

        if old > 0:
            self.stdout.write(self.style.WARNING(
                f'Found {old} old expired discounts (older than 90 days).\n'
                'Consider archiving or removing them for database cleanup.'
            ))
        else:
            self.stdout.write('No old discounts to clean up.')
