import logging
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_http_methods
from .services.species_service import get_unique_species_counts_by_list, ListType, get_occurrence_counts_by_list_type, get_top_species_occurrence_counts_by_list_type, PRIORITY_SPECIES_LISTS, PROTECTED_SPECIES_LISTS
from .services.geometry import buffer_wkt_in_meters, validate_wkt_is_polygon

logger = logging.getLogger(__name__)

# Create your views here.

# def report(request):
#     if request.method == "POST":
#         return _process_report_form(request)
#     elif request.method == "GET":
#         return _show_report_form(request)
    
@require_http_methods(["GET"])
def index(request):
    """View for defining polygon geometry and generating species alert reports."""
    context = {
        'priority_species_lists': PRIORITY_SPECIES_LISTS,
        'protected_species_lists': PROTECTED_SPECIES_LISTS,
    }
    return render(request, "species_alert/report_form.html", context)

# def validate_wkt_polygon(wkt_string):
#     """Validate that WKT string represents a single polygon."""
#     if not wkt_string:
#         return False, "WKT string is required"
    
#     # Basic WKT polygon pattern - starts with POLYGON and has coordinate pairs
#     polygon_pattern = r'^POLYGON\s*\(\s*\([^)]+\)\s*\)$'
    
#     if not re.match(polygon_pattern, wkt_string.strip(), re.IGNORECASE):
#         return False, "WKT must be a single POLYGON geometry"
    
#     return True, "Valid polygon WKT"

@require_http_methods(["POST"])
def report(request):
    """Generate species alert report from polygon input."""
    wkt = request.POST.get('wkt', '').strip()
    buffer = request.POST.get('buffer', '0').strip()
    
    # Validate WKT
    is_valid, error_message = validate_wkt_is_polygon(wkt)
    if not is_valid:
        return JsonResponse({'error': error_message}, status=400)
    
    # Validate buffer
    try:
        buffer = int(buffer) if buffer else 0
        if buffer < 0:
            return JsonResponse({'error': 'Buffer must be a non-negative integer'}, status=400)
    except ValueError:
        return JsonResponse({'error': 'Buffer must be a valid integer'}, status=400)

    buffered_wkt = wkt
    print(wkt)
    if buffer:
        print(f"Buffering WKT by {buffer} meters")
        buffered_wkt = buffer_wkt_in_meters(buffered_wkt, buffer)

    print(buffered_wkt)

    try:
        
        priority_unique_species_counts_by_list, priority_unique_species_total_count = get_unique_species_counts_by_list(ListType.PRIORITY, buffered_wkt)
        protected_unique_species_counts_by_list, protected_unique_species_total_count = get_unique_species_counts_by_list(ListType.PROTECTED, buffered_wkt)
        
        priority_occurrence_counts_by_list, priority_occurrence_total_count = get_occurrence_counts_by_list_type(ListType.PRIORITY, buffered_wkt)
        protected_occurrence_counts_by_list, protected_occurrence_total_count = get_occurrence_counts_by_list_type(ListType.PROTECTED, buffered_wkt)

        priority_top_species = get_top_species_occurrence_counts_by_list_type(ListType.PRIORITY, buffered_wkt)
        protected_top_species = get_top_species_occurrence_counts_by_list_type(ListType.PROTECTED, buffered_wkt)
        
        context = {
            "buffer": buffer,
            "buffered_wkt": buffered_wkt,
            "original_wkt": wkt,
            "priority_unique_species_counts_by_list": priority_unique_species_counts_by_list,
            "priority_unique_species_total_count": priority_unique_species_total_count,
            "protected_unique_species_counts_by_list": protected_unique_species_counts_by_list,
            "protected_unique_species_total_count": protected_unique_species_total_count,

            "priority_occurrence_counts_by_list": priority_occurrence_counts_by_list,
            "protected_occurrence_counts_by_list": protected_occurrence_counts_by_list,
            "priority_occurrence_total_count": priority_occurrence_total_count,
            "protected_occurrence_total_count": protected_occurrence_total_count,
            "priority_top_species": priority_top_species,
            "protected_top_species": protected_top_species,
        }
        return render(request, "species_alert/report.html", context)
    
    except Exception as e:
        # Handle errors from atlas records-ws API or any other errors
        logger.error(f"Error generating species alert report: {str(e)}", exc_info=True)
        error_message = f'{str(e)}'
        context = {
            'error': error_message,
            'buffer': buffer,
            'buffered_wkt': buffered_wkt,
            'original_wkt': wkt,
        }
        return render(request, 'species_alert/report.html', context)    
    

def dummy_report(request):
    """Generate a dummy priority/protected species alert report with hardcoded data for styling."""
    # Hardcoded dummy data that matches the structure of the real report
    priority_unique_species_counts_by_list = [
        {"species_list_name": "Priority Species List A", "count": 15},
        {"species_list_name": "Priority Species List B", "count": 8},
        {"species_list_name": "Priority Species List C", "count": 23},
    ]
    
    protected_unique_species_counts_by_list = [
        {"species_list_name": "Protected Species List X", "count": 12},
        {"species_list_name": "Protected Species List Y", "count": 6},
        {"species_list_name": "Protected Species List Z", "count": 19},
    ]
    
    priority_unique_species_total_count = sum(item["count"] for item in priority_unique_species_counts_by_list)
    protected_unique_species_total_count = sum(item["count"] for item in protected_unique_species_counts_by_list)
    
    priority_occurrence_counts_by_list = [
        {"species_list_name": "Priority Species List A", "count": 45},
        {"species_list_name": "Priority Species List B", "count": 32},
        {"species_list_name": "Priority Species List C", "count": 67},
    ]
    
    protected_occurrence_counts_by_list = [
        {"species_list_name": "Protected Species List X", "count": 38},
        {"species_list_name": "Protected Species List Y", "count": 21},
        {"species_list_name": "Protected Species List Z", "count": 54},
    ]
    
    priority_occurrence_total_count = sum(item["count"] for item in priority_occurrence_counts_by_list)
    protected_occurrence_total_count = sum(item["count"] for item in protected_occurrence_counts_by_list)
    
    priority_top_species = [
        {"taxon_name": "Eagle Owl (Bubo bubo)", "count": 12},
        {"taxon_name": "Red Kite (Milvus milvus)", "count": 9},
        {"taxon_name": "Otter (Lutra lutra)", "count": 7},
        {"taxon_name": "Beaver (Castor fiber)", "count": 5},
        {"taxon_name": "Golden Eagle (Aquila chrysaetos)", "count": 4},
    ]
    
    protected_top_species = [
        {"taxon_name": "Pine Marten (Martes martes)", "count": 15},
        {"taxon_name": "Wildcat (Felis silvestris)", "count": 11},
        {"taxon_name": "Water Vole (Arvicola amphibius)", "count": 8},
        {"taxon_name": "Hazel Dormouse (Muscardinus avellanarius)", "count": 6},
        {"taxon_name": "Great Crested Newt (Triturus cristatus)", "count": 4},
    ]
    
    # Dummy geometry data
    original_wkt = "POLYGON((-4.5 55.5, -4.0 55.5, -4.0 56.0, -4.5 56.0, -4.5 55.5))"
    buffer = 500
    buffered_wkt = "POLYGON((-4.505 55.495, -3.995 55.495, -3.995 56.005, -4.505 56.005, -4.505 55.495))"
    
    context = {
        "buffer": buffer,
        "buffered_wkt": buffered_wkt,
        "original_wkt": original_wkt,
        "priority_unique_species_counts_by_list": priority_unique_species_counts_by_list,
        "priority_unique_species_total_count": priority_unique_species_total_count,
        "protected_unique_species_counts_by_list": protected_unique_species_counts_by_list,
        "protected_unique_species_total_count": protected_unique_species_total_count,
        "priority_occurrence_counts_by_list": priority_occurrence_counts_by_list,
        "protected_occurrence_counts_by_list": protected_occurrence_counts_by_list,
        "priority_occurrence_total_count": priority_occurrence_total_count,
        "protected_occurrence_total_count": protected_occurrence_total_count,
        "priority_top_species": priority_top_species,
        "protected_top_species": protected_top_species,
    }
    
    return render(request, "species_alert/report.html", context)