from django.core.management.base import BaseCommand
from hotel.models import Hotel, RoomType
from hotel.pms_sync import sync_one_hotel
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile
from django.db import transaction
import requests
import urllib3
import os

# Disable insecure request warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

User = get_user_model()

class Command(BaseCommand):
    help = 'Sync hotels and room types from PMS'

    def handle(self, *args, **options):
        # Configuration
        BASE_URL = "https://aatithya1.vaiditech.in"
        API_URL = f"{BASE_URL}/channel-manager/api/v1/hotelfinder/hotels/"
        HEADERS = {
            "Authorization": "digvsludbhsdfjkgh",
            "Content-Type": "application/json"
        }

        # Get default owner (first superuser)
        owner = User.objects.filter(is_superuser=True).first()
        if not owner:
            self.stdout.write(self.style.ERROR("No superuser found. Please create a superuser first to assign as hotel owner."))
            return

        self.stdout.write(f"Using owner: {owner.username}")

        try:
            self.stdout.write(f"Fetching hotel list from {API_URL}...")
            response = requests.get(API_URL, headers=HEADERS, verify=False)
            
            if response.status_code != 200:
                self.stdout.write(self.style.ERROR(f"Failed to fetch hotels. Status: {response.status_code}"))
                return

            hotels_data = response.json()
            self.stdout.write(f"Found {len(hotels_data)} hotels.")

            for h_data in hotels_data:
                pms_id = h_data.get('id')
                if not pms_id:
                    self.stdout.write(self.style.WARNING(f"Skipping hotel without ID: {h_data.get('name')}"))
                    continue

                # Fetch details
                detail_url = f"{API_URL}{pms_id}/"
                self.stdout.write(f"Fetching details for hotel {pms_id}...")
                resp_detail = requests.get(detail_url, headers=HEADERS, verify=False)
                
                if resp_detail.status_code != 200:
                   self.stdout.write(self.style.ERROR(f"Failed to fetch details for hotel {pms_id}"))
                   continue
                
                detail = resp_detail.json()

                # Sync Hotel using shared logic
                # We need a temporary object or check existence first to pass to sync_one_hotel
                # But sync_one_hotel expects a Hotel instance.
                # Let's align the approach: 
                # 1. Reuse the get-or-create logic to ensure we have an instance.
                # 2. Call sync_one_hotel to update it.

                try:
                     hotel = Hotel.objects.get(pms_id=pms_id)
                except Hotel.DoesNotExist:
                     # Try match by name
                     hotel = Hotel.objects.filter(name=detail.get('name'), branch=detail.get('branch', 'Main')).first()
                
                if not hotel:
                    # Create a skeleton
                    hotel = Hotel.objects.create(
                        owner=owner,
                        name=detail.get('name', 'New Hotel'),
                        pms_id=pms_id,
                        branch=detail.get('branch', 'Main')
                    )
                    created = True
                else:
                    created = False

                success, msg = sync_one_hotel(hotel, detail_url, HEADERS['Authorization'])
                
                if success:
                    action = "Created" if created else "Updated"
                    self.stdout.write(self.style.SUCCESS(f"{action} Hotel: {hotel.name}"))
                else:
                    self.stdout.write(self.style.ERROR(f"Failed to sync hotel {pms_id}: {msg}"))

        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error during sync: {e}"))
