from django.shortcuts import render
import json
import requests
from django.http import JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from .models import Region, District, Category, Culture, Farmer
from django.db import transaction
import logging

logger = logging.getLogger(__name__)


class FetchAndSaveRegionsView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        url = "https://tripoli.land/api/v1/regions"
        headers = {"Authorization": "861b2a50ab7a3b40ae75375fb056c362"}

        try:
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            return JsonResponse({"error": str(e)}, status=500)

        with transaction.atomic():
            for region_data in data:
                region_id = region_data["id"]
                name_uk = region_data["name_uk"]
                slug = region_data["slug"]

                Region.create_or_update(name=name_uk, tripoli_region_id=region_id, slug=slug)

        return JsonResponse({"message": "Data successfully fetched and saved to the database"}, status=200)


class FetchAndSaveDistrictsView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        headers = {"Authorization": "861b2a50ab7a3b40ae75375fb056c362"}

        # Отримуємо всі регіони
        regions = Region.objects.all()

        with transaction.atomic():
            for region in regions:
                region_id = region.tripoli_region_id
                url = f"https://tripoli.land/api/v1/regions/{region_id}"

                try:
                    response = requests.get(url, headers=headers)
                    response.raise_for_status()
                    data = response.json()
                except requests.exceptions.RequestException as e:
                    return JsonResponse({"error": str(e)}, status=500)

                # Опрацьовуємо дані з відповіді та зберігаємо в District
                for district_data in data["districts"]:
                    district_id = district_data["id"]
                    name_uk = district_data["name_uk"]
                    slug = district_data["slug"]

                    # Отримуємо або створюємо об'єкт Region для зв'язування
                    district_region = Region.objects.get(tripoli_region_id=region_id)

                    # Створюємо або оновлюємо District
                    District.create_or_update(name=name_uk, tripoli_district_id=district_id, slug=slug, region=district_region)

        return JsonResponse({"message": "Data successfully fetched and saved to the database"}, status=200)


class FetchAndSaveCategoriesView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        url = "https://tripoli.land/api/v1/categories"
        headers = {"Authorization": "861b2a50ab7a3b40ae75375fb056c362"}

        try:
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            return JsonResponse({"error": str(e)}, status=500)

        with transaction.atomic():
            for category_data in data:
                category_id = category_data["id"]
                name_uk = category_data["name_uk"]
                slug = category_data["slug"]

                try:
                    Category.create_or_update(name=name_uk, tripoli_category_id=category_id, slug=slug)
                except Exception as e:
                    return JsonResponse({"error": f"Error processing category data: {str(e)}"}, status=500)

        return JsonResponse({"message": "Data successfully fetched and saved to the database"}, status=200)


class FetchAndSaveCulturesForAllCategoriesView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        all_categories = Category.objects.all()

        for category in all_categories:
            category_id = category.tripoli_category_id
            url = f"https://tripoli.land/api/v1/categories/{category_id}"

            try:
                response = requests.get(url, headers={"Authorization": "861b2a50ab7a3b40ae75375fb056c362"})
                response.raise_for_status()
                data = response.json()
            except requests.exceptions.RequestException as e:
                return JsonResponse({"error": f"Error fetching data for category {category_id}: {str(e)}"}, status=500)

            category_instance, created = Category.objects.get_or_create(
                tripoli_category_id=category_id,
                defaults={"name": data.get("name", ""), "slug": data.get("slug", "")}
            )

            with transaction.atomic():
                for culture_data in data.get("cultures", []):
                    culture_slug = culture_data["slug"]
                    culture_title = culture_data["title"]

                    try:
                        Culture.create_or_update(slug=culture_slug, title=culture_title, category=category_instance)
                    except Exception as e:
                        return JsonResponse({"error": f"Error processing culture data for category {category_id}: {str(e)}"}, status=500)

        return JsonResponse({"message": "Data successfully fetched and saved to the database for all categories"}, status=200)


logger = logging.getLogger(__name__)

class FetchAndSaveFarmersView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        url = "https://tripoli.land/api/v1/farmers?region_slug=luganskaya&page=9&per_page=200"
        headers = {
            "Authorization": "7560bf438e01c4a4e4ba8b2951589a71",
            "User-Agent": "MyCustomUserAgent/1.0"
        }

        try:
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            logger.error(f"Error fetching data: {str(e)}")
            return JsonResponse({"error": str(e)}, status=500)

            import os

            output_file = 'api_response.json'

            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)

            print(f"API response saved to {os.path.abspath(output_file)}")

        except requests.exceptions.RequestException as e:
            logger.error(f"Error fetching data: {str(e)}")
            return JsonResponse({"error": str(e)}, status=500)


        farmers_data = data.get("farmers", [])

        print(f"Number of farmers received: {len(farmers_data)}")

        if farmers_data:
            first_farmer = farmers_data[0]
            print("Keys in the first farmer data:")
            for key in first_farmer.keys():
                print(key)
            # Перевіряємо, чи є поле 'id'
            if 'id' in first_farmer:
                print("'id' field is present in the first farmer.")
            else:
                print("'id' field is NOT present in the first farmer.")
        else:
            print("No farmers data received.")

        farmer_ids = []
        for farmer in farmers_data:
            farmer_id = farmer.get('id')  # Або інше поле, якщо 'id' відсутній
            if farmer_id:
                farmer_ids.append(farmer_id)
            else:
                print("Farmer without 'id' field:", farmer)

        print("Farmer IDs received from API:", farmer_ids)

        with transaction.atomic():
            for farmer_data in farmers_data:
                if 'id' not in farmer_data:
                    logger.error("Error processing farmer data: Missing key 'id'")
                    return JsonResponse({"error": "Error processing farmer data: Missing key 'id'"}, status=500)

                # Перейменовуємо 'id' на 'tripoli_farmer_id'
                farmer_data['tripoli_farmer_id'] = farmer_data.pop('id')

                # Додаємо 'district_id' та 'region_id'
                farmer_data['district_id'] = farmer_data.get('district_id')
                farmer_data['district_slug'] = farmer_data.get('district_slug')
                farmer_data['region_id'] = farmer_data.get('region_id')
                farmer_data['region_slug'] = farmer_data.get('region_slug')

                # Перевіряємо, чи фермер вже існує
                tripoli_farmer_id = farmer_data['tripoli_farmer_id']
                if Farmer.objects.filter(tripoli_farmer_id=tripoli_farmer_id).exists():
                    logger.info(f"Farmer with tripoli_farmer_id {tripoli_farmer_id} already exists, skipping.")
                    continue  # Пропускаємо цього фермера та переходимо до наступного

                # Видаляємо непотрібні поля
                unwanted_fields = [
                    'belongs_company_name', 'branches', 'catalog_founders', 'catalog_lands',
                    'catalog_org_heads', 'catalog_org_registrations', 'connections', 'emails',
                    'financial_statistics', 'management', 'object_name', 'org', 'personal',
                    'phone_1_comment', 'phone_1_full_name', 'phone_1_position',
                    'phone_2_comment', 'phone_2_full_name', 'phone_2_position', 'phone_3',
                    'phone_3_comment', 'phone_3_full_name', 'phone_3_position', 'phone_4_comment',
                    'phone_4_full_name', 'phone_4_position', 'phone_5_comment',
                    'phone_5_full_name', 'phone_5_position', 'phone_6', 'phone_6_comment',
                    'phone_6_full_name', 'phone_6_position', 'phone_7', 'phone_7_comment',
                    'phone_7_full_name', 'phone_7_position', 'phone_mobile_1_comment',
                    'phone_mobile_1_full_name', 'phone_mobile_1_position', 'phone_mobile_2_comment',
                    'phone_mobile_2_full_name', 'phone_mobile_2_position', 'phone_mobile_3_comment',
                    'phone_mobile_3_full_name', 'phone_mobile_3_position', 'phone_mobile_4',
                    'phone_mobile_4_comment', 'phone_mobile_4_full_name', 'phone_mobile_4_position',
                    'phone_mobile_4_telegram', 'phone_mobile_4_viber', 'phone_mobile_5',
                    'phone_mobile_5_comment', 'phone_mobile_5_full_name', 'phone_mobile_5_position',
                    'phone_mobile_5_telegram', 'phone_mobile_5_viber', 'slug', 'transport_size',
                    'user_contacts'
                ]

                for field in unwanted_fields:
                    farmer_data.pop(field, None)

                try:
                    farmer, _ = Farmer.update_or_create_from_json(farmer_data)
                    if farmer:
                        logger.info(f"Successfully processed data for farmer with tripoli_farmer_id: {tripoli_farmer_id}")
                except Exception as e:
                    logger.error(f"Error processing farmer data: {str(e)}")
                    return JsonResponse({"error": f"Error processing farmer data: {str(e)}"}, status=500)

        return JsonResponse(data, json_dumps_params={'ensure_ascii': False, 'indent': 4})
