from django.core.management.base import BaseCommand
from core.etenders_api import get_tenders
from core.models import Tender, Company
from datetime import datetime

class Command(BaseCommand):
    help = 'Imports tenders from the eTenders API'

    def handle(self, *args, **options):
        self.stdout.write('Importing tenders from eTenders API...')
        tenders_data = get_tenders()

        if not tenders_data:
            self.stdout.write(self.style.WARNING('No tenders found or API is unavailable.'))
            return

        # For now, let's assume a default company exists.
        # A more robust implementation would be to get the company from the tender data.
        default_company, created = Company.objects.get_or_create(name='Default Company')

        imported_count = 0
        for tender_data in tenders_data:
            # Assuming the API returns these fields. This will need to be adjusted
            # based on the actual API response.
            title = tender_data.get('title')
            description = tender_data.get('description')
            deadline_str = tender_data.get('deadline')

            if not all([title, description, deadline_str]):
                self.stdout.write(self.style.WARNING(f'Skipping tender with incomplete data: {tender_data}'))
                continue

            try:
                deadline = datetime.fromisoformat(deadline_str)
            except ValueError:
                self.stdout.write(self.style.WARNING(f'Skipping tender with invalid deadline format: {deadline_str}'))
                continue

            # Check if a tender with the same title and company already exists.
            if Tender.objects.filter(title=title, company=default_company).exists():
                self.stdout.write(self.style.NOTICE(f'Tender "{title}" already exists. Skipping.'))
                continue

            Tender.objects.create(
                company=default_company,
                title=title,
                description=description,
                deadline=deadline,
            )
            imported_count += 1

        self.stdout.write(self.style.SUCCESS(f'Successfully imported {imported_count} new tenders.'))
