"""
One-command PEZAJOB setup: migrate, seed data, demo accounts, job alerts, ATS scoring.

Usage:
    python manage.py setup_pezajob
    python manage.py setup_pezajob --skip-seed
    python manage.py setup_pezajob --password MySecretPass123
"""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction

from companies.models import Company
from jobs.models import Job, JobCategory
from seekers.models import SeekerProfile
from subscriptions.models import SeekerSubscription, SubscriptionPlan

User = get_user_model()

DEMO_PASSWORD = 'Pezajob2026!'

DEMO_ACCOUNTS = [
    {
        'email': 'seeker@pezajob.com',
        'username': 'demo_seeker',
        'first_name': 'Tendai',
        'last_name': 'Ncube',
        'role': User.Role.SEEKER,
        'profile_slug': 'tendai-ncube',
        'job_alerts': True,
    },
    {
        'email': 'seeker.plus@pezajob.com',
        'username': 'demo_seeker_plus',
        'first_name': 'Grace',
        'last_name': 'Banda',
        'role': User.Role.SEEKER,
        'profile_slug': None,
        'job_alerts': True,
        'create_profile': {
            'slug': 'grace-banda',
            'full_name': 'Grace Banda',
            'headline': 'Python Developer',
            'category': 'Technology & IT',
            'category_slug': 'technology-it',
            'location': 'Lusaka',
            'years_experience': 4,
            'experience_level': SeekerProfile.ExperienceLevel.MID,
            'availability': SeekerProfile.Availability.ACTIVE,
            'skills': 'Python\nDjango\nJavaScript\nReact\nPostgreSQL\nAWS\nGit',
            'bio': 'Full-stack developer seeking senior roles in Lusaka.',
            'education': 'BSc Computer Science · UNZA · 2020',
            'experience_summary': 'Software Developer · Tech startup · 2021–Present',
            'qualification': 'BSc Computer Science',
            'is_public': True,
        },
    },
    {
        'email': 'employer@pezajob.com',
        'username': 'demo_employer',
        'first_name': 'HR',
        'last_name': 'Manager',
        'role': User.Role.COMPANY,
        'company_slug': 'airtel-zambia',
    },
]


class Command(BaseCommand):
    help = 'Full PEZAJOB setup: migrate, seed, demo accounts, subscriptions, and scoring'

    def add_arguments(self, parser):
        parser.add_argument(
            '--skip-seed',
            action='store_true',
            help='Skip seed_all (only migrate + demo accounts)',
        )
        parser.add_argument(
            '--skip-migrate',
            action='store_true',
            help='Skip database migrations',
        )
        parser.add_argument(
            '--password',
            default=DEMO_PASSWORD,
            help=f'Demo account password (default: {DEMO_PASSWORD})',
        )
        parser.add_argument(
            '--no-demo-job',
            action='store_true',
            help='Do not publish a demo job (skips job alert test email)',
        )

    def handle(self, *args, **options):
        password = options['password']

        if not options['skip_migrate']:
            self.stdout.write(self.style.MIGRATE_HEADING('Applying migrations...'))
            call_command('migrate', verbosity=0)

        if not options['skip_seed']:
            self.stdout.write(self.style.MIGRATE_HEADING('Seeding content...'))
            call_command('seed_all', verbosity=0)

        self.stdout.write(self.style.MIGRATE_HEADING('Creating demo accounts...'))
        with transaction.atomic():
            self._create_demo_accounts(password)

        self.stdout.write(self.style.MIGRATE_HEADING('Recomputing ATS match scores...'))
        call_command('recompute_match_scores', verbosity=0)

        if not options['no_demo_job']:
            self.stdout.write(self.style.MIGRATE_HEADING('Publishing demo job (triggers job alerts)...'))
            alerts_sent = self._publish_demo_job()
            if alerts_sent:
                self.stdout.write(self.style.SUCCESS(f'  {alerts_sent} job alert email(s) queued'))

        self._print_summary(password)

    def _create_demo_accounts(self, password):
        try:
            plus_plan = SubscriptionPlan.objects.get(
                slug=settings.SEEKER_PLUS_PLAN_SLUG,
                is_active=True,
            )
        except SubscriptionPlan.DoesNotExist:
            self.stdout.write(self.style.WARNING(
                'Professional Plus plan not found - run seed_plans first.'
            ))
            plus_plan = None

        for account in DEMO_ACCOUNTS:
            user, created = User.objects.update_or_create(
                email=account['email'],
                defaults={
                    'username': account['username'],
                    'first_name': account['first_name'],
                    'last_name': account['last_name'],
                    'role': account['role'],
                    'is_active': True,
                },
            )
            user.set_password(password)
            user.save(update_fields=['password'])

            action = 'Created' if created else 'Updated'
            self.stdout.write(f'  {action} {account["role"]}: {account["email"]}')

            if account['role'] == User.Role.SEEKER:
                profile = None
                if account.get('profile_slug'):
                    profile = SeekerProfile.objects.filter(slug=account['profile_slug']).first()
                    if profile:
                        profile.user = user
                        profile.save(update_fields=['user'])
                elif account.get('create_profile'):
                    profile, _ = SeekerProfile.objects.update_or_create(
                        slug=account['create_profile']['slug'],
                        defaults={**account['create_profile'], 'user': user},
                    )

                if account.get('job_alerts') and plus_plan:
                    SeekerSubscription.objects.update_or_create(
                        user=user,
                        defaults={
                            'plan': plus_plan,
                            'is_active': True,
                            'expires_at': None,
                        },
                    )
                    self.stdout.write('    [OK] Priority job alerts enabled (K20 Professional Plus)')

            if account['role'] == User.Role.COMPANY and account.get('company_slug'):
                company = Company.objects.filter(slug=account['company_slug']).first()
                if company:
                    company.owner = user
                    company.save(update_fields=['owner'])
                    Job.objects.filter(company_slug=company.slug).update(posted_by=user)
                    self.stdout.write(f'    [OK] Linked to company: {company.name}')

    def _publish_demo_job(self):
        from jobs.alert_service import dispatch_job_alerts

        employer = User.objects.filter(email='employer@pezajob.com').first()
        if not employer:
            return 0

        category, _ = JobCategory.objects.get_or_create(
            slug='technology',
            defaults={'name': 'Technology', 'icon': 'fa-laptop-code'},
        )

        job, created = Job.objects.get_or_create(
            slug='demo-python-developer-lusaka',
            defaults={
                'title': 'Python Developer',
                'company_name': 'Airtel Zambia',
                'company_slug': 'airtel-zambia',
                'company_initials': 'AT',
                'company_logo_gradient': 'linear-gradient(135deg,#e53935,#b71c1c)',
                'company_industry': 'Telecommunications',
                'location': 'Lusaka, Zambia',
                'job_type': Job.JobType.FULL_TIME,
                'experience_level': Job.ExperienceLevel.MID,
                'category': category,
                'salary_min': 12000,
                'salary_max': 18000,
                'summary': 'Build scalable web applications with Python and Django.',
                'description': (
                    'We are looking for a Python Developer to join our engineering team in Lusaka. '
                    'You will work on backend APIs, integrations, and cloud deployments.'
                ),
                'responsibilities': '\n'.join([
                    'Develop REST APIs with Python and Django',
                    'Write clean, tested, maintainable code',
                    'Collaborate with frontend developers using React',
                    'Deploy services to AWS',
                ]),
                'requirements': '\n'.join([
                    "Bachelor's degree in Computer Science or equivalent",
                    '3+ years Python development experience',
                    'Strong Django and PostgreSQL skills',
                    'Experience with Git and CI/CD',
                ]),
                'nice_to_have': '\n'.join([
                    'React or JavaScript experience',
                    'AWS certification',
                ]),
                'posted_by': employer,
                'is_active': True,
            },
        )

        if created:
            return dispatch_job_alerts(job)

        if not job.alert_logs.exists():
            return dispatch_job_alerts(job)

        self.stdout.write('  Demo job already exists - alerts previously sent, skipping.')
        return 0

    def _print_summary(self, password):
        self.stdout.write('')
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('PEZAJOB setup complete'))
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write('')
        self.stdout.write('Demo login credentials (all use the same password):')
        self.stdout.write(f'  Password: {password}')
        self.stdout.write('')
        self.stdout.write('  Job seeker (free profile):  seeker@pezajob.com')
        self.stdout.write('  Job seeker (K20 alerts):    seeker.plus@pezajob.com')
        self.stdout.write('  Employer (post jobs):       employer@pezajob.com')
        self.stdout.write('')
        self.stdout.write('URLs:')
        self.stdout.write('  Site:        http://127.0.0.1:8000/')
        self.stdout.write('  Seeker dash: http://127.0.0.1:8000/seekers/dashboard/')
        self.stdout.write('  Employer:    http://127.0.0.1:8000/employers/dashboard/')
        self.stdout.write('  ATS:         http://127.0.0.1:8000/ats/')
        self.stdout.write('  Pricing:     http://127.0.0.1:8000/subscriptions/')
        self.stdout.write('  Admin:       http://127.0.0.1:8000/django-admin/')
        self.stdout.write('')
        self.stdout.write('Start the server:  python manage.py runserver')
        self.stdout.write('')
