from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from datetime import timedelta
from career.models import JobPosition


class Command(BaseCommand):
    help = 'Populate database with European job positions only'

    def add_arguments(self, parser):
        parser.add_argument(
            '--delete-old',
            action='store_true',
            help='Delete all existing job positions before populating',
        )

    def handle(self, *args, **kwargs):
        delete_old = kwargs.get('delete_old', False)
        
        self.stdout.write(self.style.SUCCESS('Starting to populate European job positions...'))

        with transaction.atomic():
            # Delete old data if requested
            if delete_old:
                self.delete_old_data()
            
            # Create European Job Positions
            self.create_european_jobs()

        self.stdout.write(self.style.SUCCESS('\n✓ Successfully populated European job positions!'))
        self.stdout.write(f'  - Total positions: {JobPosition.objects.count()}')

    def delete_old_data(self):
        """Delete all existing job positions"""
        self.stdout.write(self.style.WARNING('Deleting old job positions...'))
        
        jobs_count = JobPosition.objects.count()
        JobPosition.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {jobs_count} job positions')
        self.stdout.write(self.style.SUCCESS('Old data deleted successfully!'))

    def create_european_jobs(self):
        """Create European job positions"""
        self.stdout.write('Creating European job positions...')
        
        jobs_data = [
            {
                'title': 'Senior Full Stack Developer',
                'department': 'Engineering',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'London, UK',
                'open_positions': 2,
                'experience_required': '5+ years',
                'salary_min': 60000,
                'salary_max': 85000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Annual bonus + Stock options + Private health insurance',
                'short_description': 'Build scalable applications with cutting-edge technologies in our London office.',
                'about_role': 'We are seeking an experienced Full Stack Developer to join our engineering team in London. You will be responsible for developing and maintaining our web applications using modern technologies and best practices. This is an exciting opportunity to work with a talented team on innovative projects.',
                'requirements': [
                    '5+ years of full-stack development experience',
                    'Strong proficiency in React, Next.js, and TypeScript',
                    'Experience with Python/Django or Node.js',
                    'Solid understanding of RESTful APIs and GraphQL',
                    'Experience with PostgreSQL and Redis',
                    'Familiarity with AWS cloud services',
                    'Right to work in the UK',
                ],
                'responsibilities': [
                    'Develop and maintain web applications',
                    'Write clean, maintainable, and efficient code',
                    'Participate in code reviews and pair programming',
                    'Collaborate with cross-functional teams',
                    'Optimize applications for performance and scalability',
                    'Mentor junior developers',
                    'Contribute to technical decision-making',
                ],
                'qualifications': [
                    'Bachelor\'s degree in Computer Science or related field',
                    'Strong problem-solving and analytical skills',
                    'Experience with version control (Git)',
                    'Good understanding of software development lifecycle',
                    'Excellent communication skills in English',
                ],
                'bonus_points': [
                    'Experience with Docker and Kubernetes',
                    'Knowledge of CI/CD pipelines (GitLab CI, GitHub Actions)',
                    'Contributions to open-source projects',
                    'Experience with microservices architecture',
                    'Knowledge of test-driven development',
                ],
                'benefits': [
                    'Competitive salary with stock options',
                    'Hybrid work model (3 days office, 2 days remote)',
                    'Latest MacBook Pro or custom PC',
                    'Learning and development budget (€2,000/year)',
                    'Private health insurance (Bupa)',
                    'Gym membership',
                    '25 days annual leave + bank holidays',
                    'Pension contribution matching',
                ],
                'start_date': 'Within 1 month',
                'status': 'active',
                'featured': True,
                'priority': 10,
            },
            {
                'title': 'Frontend Developer',
                'department': 'Engineering',
                'employment_type': 'full-time',
                'location_type': 'remote',
                'location': 'Remote (Europe)',
                'open_positions': 3,
                'experience_required': '3+ years',
                'salary_min': 45000,
                'salary_max': 65000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Performance bonus + Remote work allowance',
                'short_description': 'Create beautiful and performant user interfaces for our web applications.',
                'about_role': 'We are looking for a talented Frontend Developer to join our distributed team across Europe. You will work on building modern, responsive web applications using React and Next.js. This is a fully remote position, but we have offices in major European cities if you prefer hybrid work.',
                'requirements': [
                    '3+ years of frontend development experience',
                    'Strong proficiency in React, Next.js, and TypeScript',
                    'Experience with CSS-in-JS or Tailwind CSS',
                    'Understanding of responsive design principles',
                    'Experience with state management (Redux, Zustand)',
                    'Knowledge of modern JavaScript (ES6+)',
                    'Must be based in Europe',
                ],
                'responsibilities': [
                    'Develop responsive and accessible user interfaces',
                    'Implement design systems and component libraries',
                    'Optimize applications for performance',
                    'Write unit and integration tests',
                    'Collaborate with designers and backend developers',
                    'Participate in code reviews',
                ],
                'qualifications': [
                    'Portfolio demonstrating strong frontend skills',
                    'Experience with version control (Git)',
                    'Understanding of web accessibility standards (WCAG)',
                    'Good communication skills in English',
                ],
                'bonus_points': [
                    'Experience with Storybook',
                    'Knowledge of animation libraries (Framer Motion)',
                    'Experience with GraphQL',
                    'Understanding of SEO best practices',
                    'Experience with testing frameworks (Jest, React Testing Library)',
                ],
                'benefits': [
                    'Fully remote work (within Europe)',
                    'Competitive salary package',
                    'Remote work allowance (€500/month)',
                    'Learning and development budget',
                    'Latest MacBook Pro',
                    'Health insurance contribution',
                    'Flexible working hours',
                    '30 days annual leave',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': True,
                'priority': 9,
            },
            {
                'title': 'Backend Developer (Python/Django)',
                'department': 'Engineering',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Berlin, Germany',
                'open_positions': 2,
                'experience_required': '4+ years',
                'salary_min': 55000,
                'salary_max': 75000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ 13th month salary + Annual bonus',
                'short_description': 'Build robust backend systems and APIs using Python and Django.',
                'about_role': 'We are seeking a Backend Developer to join our engineering team in Berlin. You will work on developing scalable backend systems, RESTful APIs, and microservices using Python and Django. This is an excellent opportunity to work with modern technologies in a dynamic startup environment.',
                'requirements': [
                    '4+ years of backend development experience',
                    'Strong proficiency in Python and Django',
                    'Experience with PostgreSQL and database optimization',
                    'Understanding of RESTful API design',
                    'Experience with Redis for caching',
                    'Knowledge of Docker and containerization',
                    'Right to work in Germany',
                ],
                'responsibilities': [
                    'Design and develop backend APIs',
                    'Optimize database queries and performance',
                    'Implement authentication and authorization',
                    'Write comprehensive tests',
                    'Participate in architecture decisions',
                    'Collaborate with frontend and DevOps teams',
                ],
                'qualifications': [
                    'Bachelor\'s degree in Computer Science or related field',
                    'Strong problem-solving skills',
                    'Experience with Git and version control',
                    'Good understanding of software engineering principles',
                    'Good communication skills in English (German is a plus)',
                ],
                'bonus_points': [
                    'Experience with Celery and async task processing',
                    'Knowledge of GraphQL',
                    'Experience with AWS services',
                    'Understanding of microservices architecture',
                    'Experience with Elasticsearch',
                ],
                'benefits': [
                    'Competitive salary with 13th month',
                    'Hybrid work model',
                    'Latest development equipment',
                    'Learning budget (€1,500/year)',
                    'Public transport ticket (BVG)',
                    'Health insurance contribution',
                    '30 days annual leave',
                    'German language courses',
                ],
                'start_date': 'Within 1 month',
                'status': 'active',
                'featured': False,
                'priority': 8,
            },
            {
                'title': 'DevOps Engineer',
                'department': 'Engineering',
                'employment_type': 'full-time',
                'location_type': 'remote',
                'location': 'Remote (Europe)',
                'open_positions': 1,
                'experience_required': '4+ years',
                'salary_min': 60000,
                'salary_max': 80000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Annual bonus + Equipment budget',
                'short_description': 'Build and maintain our cloud infrastructure and CI/CD pipelines.',
                'about_role': 'We are looking for a DevOps Engineer to join our infrastructure team. You will be responsible for managing our cloud infrastructure, implementing CI/CD pipelines, and ensuring high availability of our services. This is a fully remote position open to candidates across Europe.',
                'requirements': [
                    '4+ years of DevOps or infrastructure experience',
                    'Strong experience with AWS cloud services',
                    'Proficiency with Docker and Kubernetes',
                    'Experience with CI/CD tools (GitLab CI, GitHub Actions)',
                    'Knowledge of Infrastructure as Code (Terraform, CloudFormation)',
                    'Experience with monitoring tools (Prometheus, Grafana)',
                    'Must be based in Europe',
                ],
                'responsibilities': [
                    'Manage and optimize cloud infrastructure',
                    'Design and implement CI/CD pipelines',
                    'Monitor system performance and availability',
                    'Implement security best practices',
                    'Automate deployment and scaling processes',
                    'Troubleshoot infrastructure issues',
                ],
                'qualifications': [
                    'Strong Linux/Unix administration skills',
                    'Experience with scripting (Bash, Python)',
                    'Understanding of networking and security',
                    'Good problem-solving abilities',
                    'Excellent communication skills in English',
                ],
                'bonus_points': [
                    'Experience with GitOps (ArgoCD, Flux)',
                    'Knowledge of service mesh (Istio)',
                    'Experience with multi-cloud environments',
                    'Certifications (AWS, Kubernetes)',
                    'Experience with observability tools (Datadog, New Relic)',
                ],
                'benefits': [
                    'Fully remote work',
                    'Competitive salary package',
                    'Equipment budget (€3,000)',
                    'Learning and certification budget',
                    'Health insurance contribution',
                    'Flexible working hours',
                    '30 days annual leave',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': True,
                'priority': 9,
            },
            {
                'title': 'UI/UX Designer',
                'department': 'Design',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Amsterdam, Netherlands',
                'open_positions': 1,
                'experience_required': '3+ years',
                'salary_min': 45000,
                'salary_max': 60000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ 8% holiday allowance + Annual bonus',
                'short_description': 'Create beautiful and intuitive user experiences for our products.',
                'about_role': 'We are looking for a talented UI/UX Designer to join our design team in Amsterdam. You will work closely with product managers and engineers to design user-friendly interfaces for our web and mobile applications. This role offers the opportunity to shape the user experience of our products.',
                'requirements': [
                    '3+ years of UI/UX design experience',
                    'Strong portfolio showcasing web and mobile projects',
                    'Proficiency in Figma or Sketch',
                    'Understanding of user-centered design principles',
                    'Experience with user research and usability testing',
                    'Fluent English (Dutch is a plus)',
                    'Right to work in the Netherlands',
                ],
                'responsibilities': [
                    'Create wireframes, prototypes, and high-fidelity designs',
                    'Conduct user research and usability testing',
                    'Collaborate with developers to implement designs',
                    'Maintain and evolve design systems',
                    'Present design concepts to stakeholders',
                    'Iterate on designs based on user feedback',
                ],
                'qualifications': [
                    'Portfolio demonstrating strong UI/UX design skills',
                    'Experience with design systems',
                    'Knowledge of HTML/CSS basics',
                    'Understanding of accessibility standards (WCAG)',
                    'Strong communication and presentation skills',
                ],
                'bonus_points': [
                    'Experience with motion design and animation',
                    'Knowledge of front-end development',
                    'Illustration skills',
                    'Experience with design tokens',
                    'Experience with user analytics tools',
                ],
                'benefits': [
                    'Hybrid work model',
                    'Competitive salary with 8% holiday allowance',
                    'Latest design tools and software',
                    'Learning and development budget',
                    'Health insurance contribution',
                    'Public transport card',
                    '25 days annual leave',
                    'Pension contribution',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': False,
                'priority': 7,
            },
            {
                'title': 'Product Manager',
                'department': 'Product',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Paris, France',
                'open_positions': 1,
                'experience_required': '5+ years',
                'salary_min': 65000,
                'salary_max': 85000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Annual bonus + Stock options',
                'short_description': 'Lead product strategy and development for our flagship products.',
                'about_role': 'We are looking for an experienced Product Manager to drive the vision and execution of our products from our Paris office. You will work closely with engineering, design, and marketing teams to deliver exceptional products that delight our customers. This role requires strong leadership and strategic thinking.',
                'requirements': [
                    '5+ years of product management experience',
                    'Proven track record of successful product launches',
                    'Strong understanding of agile methodologies',
                    'Excellent communication and leadership skills',
                    'Data-driven decision-making approach',
                    'Experience with product analytics tools',
                    'Right to work in France',
                ],
                'responsibilities': [
                    'Define product vision and strategy',
                    'Create and maintain product roadmap',
                    'Gather and prioritize requirements',
                    'Work with engineering team on implementation',
                    'Conduct market research and competitive analysis',
                    'Analyze product metrics and user feedback',
                    'Coordinate with stakeholders across the organization',
                ],
                'qualifications': [
                    'Bachelor\'s degree (MBA preferred)',
                    'Strong analytical and problem-solving skills',
                    'Experience with product management tools (Jira, Productboard)',
                    'Understanding of UX principles',
                    'Fluent English (French is a plus)',
                ],
                'bonus_points': [
                    'Technical background',
                    'Experience in SaaS products',
                    'Knowledge of growth strategies',
                    'Experience with A/B testing',
                    'Understanding of API design',
                ],
                'benefits': [
                    'Competitive salary with equity',
                    'Hybrid work model',
                    'Professional development budget',
                    'Health and wellness benefits',
                    'Public transport pass',
                    'Lunch vouchers',
                    '30 days annual leave + RTT',
                    'Team offsites and events',
                ],
                'start_date': 'Within 1 month',
                'status': 'active',
                'featured': True,
                'priority': 8,
            },
            {
                'title': 'Data Engineer',
                'department': 'Data',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Barcelona, Spain',
                'open_positions': 1,
                'experience_required': '4+ years',
                'salary_min': 50000,
                'salary_max': 70000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Annual bonus + Flexible benefits',
                'short_description': 'Build and maintain data pipelines and infrastructure.',
                'about_role': 'We are seeking a Data Engineer to join our data team in Barcelona. You will be responsible for designing, building, and maintaining data pipelines, data warehouses, and ETL processes. This role offers the opportunity to work with large-scale data systems and modern data technologies.',
                'requirements': [
                    '4+ years of data engineering experience',
                    'Strong proficiency in Python',
                    'Experience with SQL and database design',
                    'Knowledge of data pipeline tools (Airflow, Luigi)',
                    'Experience with cloud data warehouses (Snowflake, BigQuery, Redshift)',
                    'Understanding of ETL/ELT processes',
                    'Right to work in Spain',
                ],
                'responsibilities': [
                    'Design and build data pipelines',
                    'Maintain data warehouse infrastructure',
                    'Optimize data processing performance',
                    'Ensure data quality and reliability',
                    'Collaborate with data analysts and scientists',
                    'Document data processes and architecture',
                ],
                'qualifications': [
                    'Bachelor\'s degree in Computer Science or related field',
                    'Strong problem-solving skills',
                    'Experience with version control (Git)',
                    'Understanding of data modeling concepts',
                    'Good communication skills in English (Spanish is a plus)',
                ],
                'bonus_points': [
                    'Experience with Apache Spark',
                    'Knowledge of real-time data processing (Kafka)',
                    'Experience with dbt',
                    'Understanding of data governance',
                    'Experience with machine learning pipelines',
                ],
                'benefits': [
                    'Hybrid work model',
                    'Competitive salary package',
                    'Learning and development budget',
                    'Health insurance',
                    'Flexible working hours',
                    'Public transport card',
                    '23 days annual leave + local holidays',
                    'Flexible benefits package',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': False,
                'priority': 7,
            },
            {
                'title': 'QA Engineer',
                'department': 'Engineering',
                'employment_type': 'full-time',
                'location_type': 'remote',
                'location': 'Remote (Europe)',
                'open_positions': 2,
                'experience_required': '3+ years',
                'salary_min': 40000,
                'salary_max': 55000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Performance bonus',
                'short_description': 'Ensure quality and reliability of our software products.',
                'about_role': 'We are looking for QA Engineers to join our quality assurance team. You will be responsible for testing our web applications, writing automated tests, and ensuring the quality of our products. This is a fully remote position open to candidates across Europe.',
                'requirements': [
                    '3+ years of QA/testing experience',
                    'Experience with test automation (Selenium, Cypress, Playwright)',
                    'Knowledge of testing methodologies',
                    'Experience with API testing',
                    'Understanding of CI/CD processes',
                    'Strong attention to detail',
                    'Must be based in Europe',
                ],
                'responsibilities': [
                    'Design and execute test plans',
                    'Write and maintain automated tests',
                    'Perform manual testing when needed',
                    'Report and track bugs',
                    'Collaborate with development teams',
                    'Participate in release processes',
                ],
                'qualifications': [
                    'Strong analytical and problem-solving skills',
                    'Experience with version control (Git)',
                    'Understanding of software development lifecycle',
                    'Good communication skills in English',
                ],
                'bonus_points': [
                    'Experience with performance testing',
                    'Knowledge of security testing',
                    'Experience with mobile app testing',
                    'Programming skills (Python, JavaScript)',
                    'Experience with test management tools',
                ],
                'benefits': [
                    'Fully remote work',
                    'Competitive salary package',
                    'Learning and development budget',
                    'Health insurance contribution',
                    'Flexible working hours',
                    '30 days annual leave',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': False,
                'priority': 6,
            },
            {
                'title': 'Marketing Manager',
                'department': 'Marketing',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Dublin, Ireland',
                'open_positions': 1,
                'experience_required': '4+ years',
                'salary_min': 50000,
                'salary_max': 70000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Annual bonus + Health insurance',
                'short_description': 'Lead our marketing efforts and grow our brand presence in Europe.',
                'about_role': 'We are looking for a Marketing Manager to join our marketing team in Dublin. You will be responsible for developing and executing marketing strategies to increase brand awareness and drive customer acquisition across European markets. This role offers the opportunity to shape our marketing approach.',
                'requirements': [
                    '4+ years of marketing experience',
                    'Proven track record of successful marketing campaigns',
                    'Strong understanding of digital marketing channels',
                    'Experience with marketing automation tools',
                    'Excellent analytical and communication skills',
                    'Experience with B2B marketing',
                    'Right to work in Ireland',
                ],
                'responsibilities': [
                    'Develop and execute marketing strategies',
                    'Manage digital marketing campaigns',
                    'Oversee content marketing initiatives',
                    'Analyze campaign performance and ROI',
                    'Manage marketing budget',
                    'Collaborate with sales and product teams',
                    'Coordinate events and webinars',
                ],
                'qualifications': [
                    'Bachelor\'s degree in Marketing or related field',
                    'Experience with Google Analytics and marketing tools',
                    'Strong project management skills',
                    'Creative thinking and problem-solving abilities',
                    'Excellent communication skills in English',
                ],
                'bonus_points': [
                    'Experience with HubSpot or similar platforms',
                    'Knowledge of SEO and content marketing',
                    'Video production skills',
                    'Experience with paid advertising',
                    'Multilingual (French, German, Spanish)',
                ],
                'benefits': [
                    'Hybrid work model',
                    'Competitive salary package',
                    'Marketing conferences and events budget',
                    'Professional development opportunities',
                    'Health insurance',
                    'Public transport card',
                    '25 days annual leave',
                    'Pension contribution',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': False,
                'priority': 6,
            },
            {
                'title': 'Sales Development Representative',
                'department': 'Sales',
                'employment_type': 'full-time',
                'location_type': 'hybrid',
                'location': 'Warsaw, Poland',
                'open_positions': 2,
                'experience_required': '1+ years',
                'salary_min': 35000,
                'salary_max': 45000,
                'salary_currency': 'EUR',
                'salary_period': 'per year',
                'salary_additional': '+ Commission + Annual bonus',
                'short_description': 'Generate leads and build relationships with potential customers.',
                'about_role': 'We are looking for Sales Development Representatives to join our sales team in Warsaw. You will be responsible for prospecting, qualifying leads, and setting up meetings for our sales team. This is an excellent entry-level opportunity with growth potential.',
                'requirements': [
                    '1+ years of sales or customer service experience',
                    'Strong communication and interpersonal skills',
                    'Self-motivated and goal-oriented',
                    'Experience with CRM systems (Salesforce, HubSpot)',
                    'Fluent English (Polish is a plus)',
                    'Right to work in Poland',
                ],
                'responsibilities': [
                    'Prospect and qualify leads',
                    'Conduct outbound outreach (email, phone, LinkedIn)',
                    'Schedule meetings for sales team',
                    'Maintain CRM database',
                    'Follow up with prospects',
                    'Achieve monthly quotas',
                ],
                'qualifications': [
                    'Strong communication skills',
                    'Ability to work in a fast-paced environment',
                    'Basic understanding of sales processes',
                    'Proficiency with Microsoft Office',
                ],
                'bonus_points': [
                    'Experience in B2B sales',
                    'Knowledge of the tech industry',
                    'Multilingual skills',
                    'Experience with sales tools',
                ],
                'benefits': [
                    'Hybrid work model',
                    'Competitive base salary + commission',
                    'Sales training and development',
                    'Health insurance',
                    'Public transport card',
                    '20 days annual leave',
                    'Career growth opportunities',
                ],
                'start_date': 'ASAP',
                'status': 'active',
                'featured': False,
                'priority': 5,
            },
        ]

        created_count = 0
        for job_data in jobs_data:
            # Generate slug from title
            slug = job_data['title'].lower().replace(' ', '-').replace('/', '-').replace('(', '').replace(')', '')
            
            job, created = JobPosition.objects.get_or_create(
                slug=slug,
                defaults=job_data
            )
            if created:
                created_count += 1
                self.stdout.write(
                    self.style.SUCCESS(f'  ✓ Created job: {job.title} - {job.location}')
                )
            else:
                self.stdout.write(
                    f'  - Job already exists: {job.title} - {job.location}'
                )

        self.stdout.write(
            self.style.SUCCESS(f'\n✓ Created {created_count} European job position(s)!')
        )

