from django.shortcuts import render
from django.http import JsonResponse
from django.db import connection
from django.views.decorators.csrf import csrf_exempt
from .models import GwyneddNrwPh1IntertidalBiotopeSites, IndicatorSpecies, GwyneddNrwPh1IntertidalBiotope, BiotopeCode
# from .services import get_site_image_url  # Disabled photo functionality
import json
import logging

logger = logging.getLogger(__name__)

def home(request):
    """Home page with Leaflet map showing Gwynedd layers."""
    return render(request, 'habitats_and_biotopes/home.html')


def get_site_boundary(request, site_id):
    """
    API endpoint to return GeoJSON boundary for a specific site.
    
    Args:
        site_id: The siteid of the site
    """
    try:
        site_id_float = float(site_id)
        site = GwyneddNrwPh1IntertidalBiotopeSites.objects.filter(siteid=site_id_float).first()
        
        if not site or not site.geom:
            return JsonResponse({'error': 'Site not found or has no geometry'}, status=404)
        
        # Convert geometry to GeoJSON using PostGIS
        # First check the SRID and transform to 4326 if needed
        with connection.cursor() as cursor:
            # Get the SRID of the geometry
            cursor.execute("""
                SELECT ST_SRID(geom) as srid
                FROM gwynedd_nrw_ph1_intertidal_biotope_sites
                WHERE siteid = %s AND geom IS NOT NULL;
            """, [site_id_float])
            srid_result = cursor.fetchone()
            
            srid = srid_result[0] if srid_result and srid_result[0] else None
            
            # Build the transform expression - if SRID is 0 or NULL, try 27700 (British National Grid)
            # If already 4326, no transform needed
            if srid == 4326 or srid == 0 or srid is None:
                if srid == 4326:
                    transform_expr = "geom"
                else:
                    # Try transforming from 27700 (most likely for UK data)
                    transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
            else:
                transform_expr = f"ST_Transform(geom, 4326)"
            
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'Feature',
                    'geometry', ST_AsGeoJSON({transform_expr})::json,
                    'properties', json_build_object(
                        'siteid', siteid,
                        'siteno', siteno,
                        'image_url', NULL
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope_sites
                WHERE siteid = %s AND geom IS NOT NULL;
            """, [site_id_float])
            result = cursor.fetchone()
            
            if result and result[0]:
                # Disabled photo functionality
                # geojson_data = result[0]
                # # Add image URL to properties
                # image_url = get_site_image_url(site_id_float)
                # if image_url and 'properties' in geojson_data:
                #     geojson_data['properties']['image_url'] = image_url
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
                
    except ValueError:
        return JsonResponse({'error': 'Invalid site ID'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


def get_all_site_boundaries(request):
    """
    API endpoint to return GeoJSON boundaries for all sites.
    """
    try:
        sites = GwyneddNrwPh1IntertidalBiotopeSites.objects.all().order_by('siteno')
        transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'FeatureCollection',
                    'features', COALESCE(
                        json_agg(
                            json_build_object(
                                'type', 'Feature',
                                'geometry', ST_AsGeoJSON({transform_expr})::json,
                                'properties', json_build_object(
                                    'siteid', siteid,
                                    'siteno', siteno
                                )
                            )
                        ),
                        '[]'::json
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope_sites
                WHERE geom IS NOT NULL;
            """)
            result = cursor.fetchone()
            if result and result[0]:
                # Disabled photo functionality
                # geojson_data = result[0]
                # # Add image URLs to each feature
                # if 'features' in geojson_data:
                #     for feature in geojson_data['features']:
                #         if 'properties' in feature and 'siteid' in feature['properties']:
                #             site_id = feature['properties']['siteid']
                #             if site_id:
                #                 image_url = get_site_image_url(float(site_id))
                #                 if image_url:
                #                     feature['properties']['image_url'] = image_url
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
        
    except Exception as e:  
        print(e)
        return JsonResponse({'error': str(e)}, status=500)


def get_biotope_code(request, biotope_code):
    """
    API endpoint to return biotope code information (title) for a specific biotope code.
    
    Args:
        biotope_code: The f2004_code (biotope code) to look up
    """
    try:
        # Look up the biotope code in the database
        biotope = BiotopeCode.objects.filter(code=biotope_code).first()
        
        if not biotope:
            return JsonResponse({
                'code': biotope_code,
                'title': None
            })
        
        return JsonResponse({
            'code': biotope.code,
            'title': biotope.title
        })
        
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)




def get_indicator_species(request, f2004_code):
    """
    Endpoint to return indicator species for a specific f2004_code.
    Returns HTML partial template for HTMX requests.    
    """
    try:
        species_list = []
        species = IndicatorSpecies.objects.filter(f2004_code=f2004_code).order_by('species_name')
        
        for s in species:
            species_list.append({
                'species_name': s.species_name,
            })
        
        context = {
            'f2004_code': f2004_code,
            'species': species_list,
            'species_count': len(species_list),
        }
        
        return render(request, 'habitats_and_biotopes/partials/indicator_species.html', context)
        
    except Exception as e:
        # Log the full exception with traceback
        logger.error(f'Error loading indicator species for code {f2004_code}: {str(e)}', exc_info=True)
        # Return error message in partial format
        return render(request, 'habitats_and_biotopes/partials/indicator_species.html', {
            'f2004_code': f2004_code,
            'error': str(e),
            'species': [],
            'species_count': 0,
        }, status=500)


# ============================================================================
# NOt USED ANYMORE
# ============================================================================

def get_biotopes_for_site(request, site_id):
    """
    API endpoint to return GeoJSON biotopes for a specific site.
    
    Args:
        site_id: The siteid of the site
    """
    try:
        site_id_float = float(site_id)
        transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
        
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'FeatureCollection',
                    'features', COALESCE(
                        json_agg(
                            json_build_object(
                                'type', 'Feature',
                                'geometry', ST_AsGeoJSON({transform_expr})::json,
                                'properties', json_build_object(
                                    'biotopeid', biotopeid,
                                    'biotope', biotope,
                                    'lifeform', lifeform,
                                    'areaha', areaha,
                                    'siteid', siteid,
                                    'siteno', siteno,
                                    'last_visit', last_visit,
                                    'f2004_code', f2004_code
                                )
                            )
                        ),
                        '[]'::json
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope
                WHERE siteid = %s AND geom IS NOT NULL;
            """, [site_id_float])
            result = cursor.fetchone()
            
            if result and result[0]:
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
                
    except ValueError:
        return JsonResponse({'error': 'Invalid site ID'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

# ============================================================================
# NOt USED ANYMORE
# ============================================================================

def get_all_biotopes(request):
    """
    API endpoint to return GeoJSON biotopes for all sites.
    """
    try:
        transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
        
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'FeatureCollection',
                    'features', COALESCE(
                        json_agg(
                            json_build_object(
                                'type', 'Feature',
                                'geometry', ST_AsGeoJSON({transform_expr})::json,
                                'properties', json_build_object(
                                    'biotopeid', biotopeid,
                                    'biotope', biotope,
                                    'lifeform', lifeform,
                                    'areaha', areaha,
                                    'siteid', siteid,
                                    'siteno', siteno,
                                    'last_visit', last_visit,
                                    'f2004_code', f2004_code
                                )
                            )
                        ),
                        '[]'::json
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope
                WHERE geom IS NOT NULL;
            """)
            result = cursor.fetchone()
            
            if result and result[0]:
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
                
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

# ============================================================================
# NOt USED ANYMORE
# ============================================================================

def get_notes_for_site(request, site_id):
    """
    API endpoint to return GeoJSON notes points for a specific site.
    
    Args:
        site_id: The siteid of the site
    """
    try:
        site_id_float = float(site_id)
        transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
        
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'FeatureCollection',
                    'features', COALESCE(
                        json_agg(
                            json_build_object(
                                'type', 'Feature',
                                'geometry', ST_AsGeoJSON({transform_expr})::json,
                                'properties', json_build_object(
                                    'id', id,
                                    'objectid', objectid,
                                    'siteid', siteid,
                                    'siteno', siteno,
                                    'targetnote', targetnote,
                                    'xcoordinat', xcoordinat,
                                    'ycoordinat', ycoordinat,
                                    'osgridref', osgridref,
                                    'targetno0', targetno0,
                                    'targetno1', targetno1,
                                    'accesslink', accesslink
                                )
                            )
                        ),
                        '[]'::json
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope_notes
                WHERE siteid = %s AND geom IS NOT NULL;
            """, [site_id_float])
            result = cursor.fetchone()
            
            if result and result[0]:
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
                
    except ValueError:
        return JsonResponse({'error': 'Invalid site ID'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

# ============================================================================
# NOt USED ANYMORE
# ============================================================================

def get_all_notes(request):
    """
    API endpoint to return GeoJSON notes points for all sites.
    """
    try:
        transform_expr = "ST_Transform(ST_SetSRID(geom, 27700), 4326)"
        
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT json_build_object(
                    'type', 'FeatureCollection',
                    'features', COALESCE(
                        json_agg(
                            json_build_object(
                                'type', 'Feature',
                                'geometry', ST_AsGeoJSON({transform_expr})::json,
                                'properties', json_build_object(
                                    'id', id,
                                    'objectid', objectid,
                                    'siteid', siteid,
                                    'siteno', siteno,
                                    'targetnote', targetnote,
                                    'xcoordinat', xcoordinat,
                                    'ycoordinat', ycoordinat,
                                    'osgridref', osgridref,
                                    'targetno0', targetno0,
                                    'targetno1', targetno1,
                                    'accesslink', accesslink
                                )
                            )
                        ),
                        '[]'::json
                    )
                )
                FROM gwynedd_nrw_ph1_intertidal_biotope_notes
                WHERE geom IS NOT NULL;
            """)
            result = cursor.fetchone()
            
            if result and result[0]:
                return JsonResponse(result[0], safe=False)
            else:
                return JsonResponse({'error': 'Failed to convert geometry'}, status=500)
                
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
