"""
Management command to seed businesses for all dashboard sections.
Creates 10 businesses per section: Featured, Popular, Verified, Home Services.
Each business gets a profile image and 2 gallery images.

Usage:
    python manage.py seed_businesses
    python manage.py seed_businesses --clear  # Delete seeded data first
"""
import io
import random
from decimal import Decimal
from datetime import time

from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from django.contrib.auth import get_user_model
from PIL import Image, ImageDraw, ImageFont

from business.models import (
    Category, SubCategory, Business, BusinessImage, BusinessHours
)

User = get_user_model()

# Lahore area coordinates - clustered near user location (31.5853, 74.4214)
LAHORE_LOCATIONS = [
    ('Samanabad', Decimal('31.5780'), Decimal('74.4100')),
    ('Mughal Pura', Decimal('31.5890'), Decimal('74.4180')),
    ('Shahdara', Decimal('31.5950'), Decimal('74.4250')),
    ('Baghbanpura', Decimal('31.5830'), Decimal('74.4300')),
    ('Misri Shah', Decimal('31.5800'), Decimal('74.4050')),
    ('Badami Bagh', Decimal('31.5750'), Decimal('74.4200')),
    ('Mughalpura', Decimal('31.5870'), Decimal('74.4150')),
    ('Shalimar Garden', Decimal('31.5920'), Decimal('74.4100')),
    ('GT Road Area', Decimal('31.5860'), Decimal('74.4280')),
    ('Daroghawala', Decimal('31.5980'), Decimal('74.4050')),
    ('Model Town', Decimal('31.4804'), Decimal('74.3239')),
    ('Gulberg III', Decimal('31.5204'), Decimal('74.3487')),
    ('DHA Phase 5', Decimal('31.4504'), Decimal('74.3587')),
    ('Johar Town', Decimal('31.4697'), Decimal('74.2728')),
    ('Garden Town', Decimal('31.5310'), Decimal('74.3487')),
]

# Color palettes for generating images
COLORS = [
    '#2E7D32', '#1565C0', '#C62828', '#6A1B9A', '#E65100',
    '#00838F', '#AD1457', '#283593', '#558B2F', '#4E342E',
    '#37474F', '#00695C', '#BF360C', '#1A237E', '#880E4F',
]

CATEGORIES_DATA = [
    {'name': 'Art and Entertainment', 'description': 'Creative arts, media, and entertainment services'},
    {'name': 'Beauty and Wellness', 'description': 'Salons, spas, fitness, and wellness centers'},
    {'name': 'Engineering and Construction', 'description': 'Construction, renovation, and engineering services'},
    {'name': 'Health and Medical', 'description': 'Doctors, clinics, pharmacies, and medical services'},
    {'name': 'Home and Services', 'description': 'Home maintenance, cleaning, and repair services'},
    {'name': 'Food and Restaurants', 'description': 'Restaurants, cafes, catering, and food delivery'},
    {'name': 'Education and Training', 'description': 'Schools, tutoring, coaching, and training centers'},
    {'name': 'Automotive', 'description': 'Vehicle repair, detailing, and automotive services'},
    {'name': 'Shopping and Retail', 'description': 'Shops, stores, and retail outlets'},
    {'name': 'Technology', 'description': 'IT services, computer repair, and tech solutions'},
]

# Business templates per section
FEATURED_BUSINESSES = [
    ('Royal Banquet Hall', 'Art and Entertainment', 'Premium banquet hall for weddings and corporate events with world-class facilities.'),
    ('Glamour Beauty Salon', 'Beauty and Wellness', 'Top-rated beauty salon offering haircuts, facials, bridal makeup, and spa services.'),
    ('Elite Construction Co.', 'Engineering and Construction', 'Leading construction company delivering quality residential and commercial projects.'),
    ('City Hospital & Clinics', 'Health and Medical', 'Multi-specialty hospital with 24/7 emergency services and experienced doctors.'),
    ('HomeFix Services', 'Home and Services', 'Complete home maintenance solutions including plumbing, electrical, and painting.'),
    ('Spice Garden Restaurant', 'Food and Restaurants', 'Authentic Pakistani cuisine in a beautiful garden setting with live music.'),
    ('Bright Future Academy', 'Education and Training', 'Premier coaching center for O/A levels, MDCAT, and competitive exam preparation.'),
    ('AutoCare Premium', 'Automotive', 'Full-service auto workshop with certified mechanics and genuine spare parts.'),
    ('Fashion Hub Outlet', 'Shopping and Retail', 'Trendy clothing store featuring local and international fashion brands.'),
    ('TechZone Solutions', 'Technology', 'Professional IT services, custom software development, and tech support.'),
]

POPULAR_BUSINESSES = [
    ('Melody Music Studio', 'Art and Entertainment', 'Professional music studio offering recording, mixing, and music production services.'),
    ('Zen Spa & Wellness', 'Beauty and Wellness', 'Luxurious spa experience with traditional and modern wellness therapies.'),
    ('BuildRight Engineers', 'Engineering and Construction', 'Certified civil engineers providing structural design and project management.'),
    ('MedCare Pharmacy', 'Health and Medical', 'Well-stocked pharmacy with home delivery and 24/7 availability.'),
    ('CleanPro Services', 'Home and Services', 'Professional deep cleaning, fumigation, and home sanitation services.'),
    ('Tandoor Express', 'Food and Restaurants', 'Famous for fresh tandoori naan, tikka, and traditional BBQ platters.'),
    ('Smart Learners Institute', 'Education and Training', 'Modern teaching methods with experienced faculty for all grade levels.'),
    ('Turbo Mechanics', 'Automotive', 'Expert car and bike repair with computerized diagnostics and quick service.'),
    ('Gadget World', 'Shopping and Retail', 'Latest smartphones, laptops, and accessories at competitive prices.'),
    ('WebPro Digital', 'Technology', 'Web development, app design, and digital marketing services for businesses.'),
]

VERIFIED_BUSINESSES = [
    ('Creative Minds Studio', 'Art and Entertainment', 'Award-winning creative agency for graphic design, photography, and videography.'),
    ('Glow Up Aesthetics', 'Beauty and Wellness', 'Advanced skincare treatments, laser therapy, and cosmetic procedures.'),
    ('Solid Foundations Ltd.', 'Engineering and Construction', 'Trusted name in foundation work, steel structures, and renovation projects.'),
    ('HealthFirst Diagnostics', 'Health and Medical', 'State-of-the-art diagnostic lab with accurate and fast test results.'),
    ('PowerFix Electricals', 'Home and Services', 'Licensed electricians for residential and commercial electrical installations.'),
    ('Biryani House', 'Food and Restaurants', 'Legendary Lahori biryani with secret family recipe since 1985.'),
    ('Cambridge Tutors', 'Education and Training', 'Expert tutoring for Cambridge system students with proven track record.'),
    ('Golden Wheels Auto', 'Automotive', 'Car detailing, ceramic coating, and paint protection film specialists.'),
    ('BookWorm Store', 'Shopping and Retail', 'Largest collection of academic, fiction, and reference books in the city.'),
    ('CloudNet IT Services', 'Technology', 'Cloud hosting, network setup, and cybersecurity solutions for enterprises.'),
]

HOME_SERVICE_BUSINESSES = [
    ('EventPro Planners', 'Art and Entertainment', 'Complete event planning and decoration services at your doorstep.'),
    ('Beauty at Home', 'Beauty and Wellness', 'Professional beauticians providing salon services at your home.'),
    ('RenovateNow Team', 'Engineering and Construction', 'Home renovation, waterproofing, and interior design services at your place.'),
    ('Doctor on Call', 'Health and Medical', 'Experienced doctors providing home visits for checkups and minor treatments.'),
    ('PlumbMaster Services', 'Home and Services', 'Emergency plumbing repairs, pipe fitting, and water tank installation.'),
    ('Chef at Home', 'Food and Restaurants', 'Professional chefs cooking fresh meals and party food at your home.'),
    ('Home Tutor Network', 'Education and Training', 'Qualified home tutors for all subjects from primary to university level.'),
    ('Mobile Mechanic Lahore', 'Automotive', 'On-spot vehicle repair, battery jump-start, and tyre change services.'),
    ('Furniture Assembly Pro', 'Shopping and Retail', 'Expert furniture assembly, installation, and moving services at home.'),
    ('PC Doctor Home Service', 'Technology', 'Computer repair, virus removal, and network setup at your doorstep.'),
]


def generate_business_image(business_name, color, width=800, height=600):
    """Generate a placeholder business image with name and color."""
    img = Image.new('RGB', (width, height), color)
    draw = ImageDraw.Draw(img)

    # Add a subtle gradient overlay
    for y in range(height):
        alpha = int(60 * (y / height))
        draw.line([(0, y), (width, y)], fill=(0, 0, 0, alpha))

    # Draw business initials in center
    initials = ''.join(word[0].upper() for word in business_name.split()[:2])

    # Use default font with larger size
    try:
        font = ImageFont.truetype("arial.ttf", 120)
        small_font = ImageFont.truetype("arial.ttf", 28)
    except (OSError, IOError):
        font = ImageFont.load_default()
        small_font = font

    # Draw white circle background for initials
    circle_size = 180
    cx, cy = width // 2, height // 2 - 30
    draw.ellipse(
        [cx - circle_size // 2, cy - circle_size // 2,
         cx + circle_size // 2, cy + circle_size // 2],
        fill='white', outline='white'
    )

    # Draw initials
    bbox = draw.textbbox((0, 0), initials, font=font)
    tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
    draw.text((cx - tw // 2, cy - th // 2 - 10), initials, fill=color, font=font)

    # Draw business name at bottom
    bbox2 = draw.textbbox((0, 0), business_name, font=small_font)
    tw2 = bbox2[2] - bbox2[0]
    # White semi-transparent bar at bottom
    draw.rectangle([0, height - 70, width, height], fill=(0, 0, 0))
    draw.text(
        ((width - tw2) // 2, height - 55),
        business_name, fill='white', font=small_font
    )

    # Save to bytes
    buffer = io.BytesIO()
    img.save(buffer, format='JPEG', quality=85)
    buffer.seek(0)
    return buffer


class Command(BaseCommand):
    help = 'Seed 10 businesses per dashboard section (Featured, Popular, Verified, Home Services) with images'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear', action='store_true',
            help='Delete previously seeded businesses before creating new ones',
        )

    def handle(self, *args, **options):
        if options['clear']:
            self.stdout.write('Clearing previously seeded businesses...')
            Business.objects.filter(owner__email='seed@discovr.com').delete()
            User.objects.filter(email='seed@discovr.com').delete()
            self.stdout.write(self.style.SUCCESS('Cleared.'))

        # 1. Create seed user
        user, created = User.objects.get_or_create(
            email='seed@discovr.com',
            defaults={
                'first_name': 'Seed',
                'last_name': 'Owner',
                'is_email_verified': True,
            }
        )
        if created:
            user.set_password('seedpass123')
            user.save()
            self.stdout.write(self.style.SUCCESS('Created seed user: seed@discovr.com'))

        # 2. Ensure categories exist
        categories = {}
        for cat_data in CATEGORIES_DATA:
            cat, _ = Category.objects.get_or_create(
                name=cat_data['name'],
                defaults={'description': cat_data['description']}
            )
            categories[cat.name] = cat

        self.stdout.write(self.style.SUCCESS(f'Categories ready: {len(categories)}'))

        # 3. Create businesses per section
        sections = [
            ('Featured', FEATURED_BUSINESSES, {'is_featured': True, 'is_verified': True}),
            ('Popular', POPULAR_BUSINESSES, {'is_featured': False, 'is_verified': True}),
            ('Verified', VERIFIED_BUSINESSES, {'is_featured': False, 'is_verified': True}),
            ('Home Services', HOME_SERVICE_BUSINESSES, {'is_featured': False, 'is_verified': True, 'provides_home_service': True}),
        ]

        total_created = 0
        for section_name, business_list, flags in sections:
            self.stdout.write(f'\n--- Creating {section_name} businesses ---')
            for i, (title, cat_name, description) in enumerate(business_list):
                # Skip if already exists
                if Business.objects.filter(title=title).exists():
                    self.stdout.write(f'  Already exists: {title}')
                    continue

                # Pick a random location
                loc = LAHORE_LOCATIONS[i % len(LAHORE_LOCATIONS)]
                area_name, lat, lng = loc
                color = COLORS[i % len(COLORS)]

                # Determine rating based on section
                if section_name == 'Popular':
                    avg_rating = Decimal(str(round(random.uniform(4.2, 5.0), 2)))
                    total_reviews = random.randint(15, 80)
                elif section_name == 'Verified':
                    avg_rating = Decimal(str(round(random.uniform(4.0, 4.9), 2)))
                    total_reviews = random.randint(10, 50)
                elif section_name == 'Featured':
                    avg_rating = Decimal(str(round(random.uniform(3.5, 5.0), 2)))
                    total_reviews = random.randint(5, 60)
                else:
                    avg_rating = Decimal(str(round(random.uniform(3.0, 4.8), 2)))
                    total_reviews = random.randint(3, 30)

                # Create business
                business = Business.objects.create(
                    owner=user,
                    title=title,
                    description=description,
                    latitude=lat,
                    longitude=lng,
                    address=f'{area_name}, Lahore',
                    city='Lahore',
                    country='Pakistan',
                    phone_number=f'+9230{random.randint(10000000, 99999999)}',
                    whatsapp_number=f'+9230{random.randint(10000000, 99999999)}',
                    is_verified=flags.get('is_verified', True),
                    is_featured=flags.get('is_featured', False),
                    provides_home_service=flags.get('provides_home_service', False),
                    average_rating=avg_rating,
                    total_reviews=total_reviews,
                )

                # Link category
                if cat_name in categories:
                    business.categories.add(categories[cat_name])

                # Generate & attach profile image
                profile_buf = generate_business_image(title, color, 400, 400)
                business.profile_image.save(
                    f'seed_{business.id}_profile.jpg',
                    ContentFile(profile_buf.read()),
                    save=True,
                )

                # Generate & attach 2 gallery images
                for img_idx in range(2):
                    gallery_buf = generate_business_image(
                        title, COLORS[(i + img_idx + 3) % len(COLORS)]
                    )
                    BusinessImage.objects.create(
                        business=business,
                        image=ContentFile(
                            gallery_buf.read(),
                            name=f'seed_{business.id}_gallery_{img_idx}.jpg',
                        ),
                        is_main=(img_idx == 0),
                    )

                # Add operating hours (Mon-Sat 9AM-9PM, Sun closed)
                for day in range(7):
                    BusinessHours.objects.create(
                        business=business,
                        day_of_week=day,
                        opening_time=time(9, 0) if day < 6 else None,
                        closing_time=time(21, 0) if day < 6 else None,
                        is_closed=(day == 6),
                        is_24_hours=False,
                    )

                total_created += 1
                self.stdout.write(self.style.SUCCESS(
                    f'  Created: {title} [{section_name}] '
                    f'(rating: {avg_rating}, reviews: {total_reviews})'
                ))

        self.stdout.write('')
        self.stdout.write(self.style.SUCCESS(f'Done! Created {total_created} new businesses.'))
        self.stdout.write(self.style.SUCCESS(f'Total businesses in DB: {Business.objects.count()}'))
        self.stdout.write('')
        self.stdout.write('Section breakdown:')
        self.stdout.write(f'  Featured:      {Business.objects.filter(is_featured=True).count()}')
        self.stdout.write(f'  Verified:      {Business.objects.filter(is_verified=True).count()}')
        self.stdout.write(f'  Home Services: {Business.objects.filter(provides_home_service=True).count()}')
        self.stdout.write(f'  Popular (rating>=4.0): {Business.objects.filter(average_rating__gte=4.0).count()}')
        self.stdout.write('')
        self.stdout.write('Run: python manage.py seed_businesses --clear  to remove seeded data')
