"""
Helper to format custom criteria data for GPT prompt
"""

def format_custom_data_for_prompt(property_data):
    """
    Format custom criteria data into readable text for GPT prompt

    Args:
        property_data: dict with lat, lon, and optionally custom criteria results

    Returns:
        str: Formatted text block for insertion into prompt
    """

    # Check if we have custom criteria data
    custom_score = property_data.get('custom_score', 0)

    if not custom_score or custom_score == 0:
        return """
[GEEN OBJECTIEVE DATA BESCHIKBAAR]
Er is nog geen objectieve klimaat- en locatiedata verzameld voor dit pand.
Baseer je analyse op de beschrijving en algemene kennis van de regio.
"""

    # Build formatted data section
    sections = []

    # Header
    sections.append("💡 BESCHIKBARE OBJECTIEVE DATA (gebruik deze in je analyse!):")
    sections.append("")

    # Climate data
    rainfall = property_data.get('custom_rainfall_data')
    temperature = property_data.get('custom_temperature_data')

    if rainfall:
        try:
            rainfall_data = eval(rainfall) if isinstance(rainfall, str) else rainfall
            annual_mm = rainfall_data.get('annual_rainfall_mm', 'onbekend')
            if annual_mm != 'onbekend':
                sections.append(f"🌧️ NEERSLAG: {annual_mm:.0f} mm per jaar")
                if 800 <= annual_mm <= 1300:
                    sections.append(f"   → Uitstekend voor landbouw (ideaal voor groenteteelt)")
                elif 600 <= annual_mm < 800:
                    sections.append(f"   → Goed voor landbouw (irrigatie kan nodig zijn in droge periodes)")
                elif annual_mm < 600:
                    sections.append(f"   → Beperkte neerslag (irrigatie noodzakelijk voor market garden)")
                else:
                    sections.append(f"   → Hoge neerslag (goede watervoorziening, mogelijk drainage nodig)")
                sections.append("")
        except:
            pass

    if temperature:
        try:
            temp_data = eval(temperature) if isinstance(temperature, str) else temperature
            growing_days = temp_data.get('growing_days', 'onbekend')
            avg_temp = temp_data.get('avg_temp_c', 'onbekend')

            if growing_days != 'onbekend':
                sections.append(f"🌡️ KLIMAAT:")
                sections.append(f"   • Groeidagen per jaar (>5°C): {growing_days} dagen")
                if isinstance(avg_temp, (int, float)):
                    sections.append(f"   • Gemiddelde temperatuur: {avg_temp:.1f}°C")

                if growing_days >= 280:
                    sections.append(f"   → Uitstekend klimaat (jaar-rond teelt mogelijk)")
                elif growing_days >= 240:
                    sections.append(f"   → Goed klimaat (lang teeltseizoen)")
                elif growing_days >= 180:
                    sections.append(f"   → Gemiddeld klimaat (normaal teeltseizoen)")
                else:
                    sections.append(f"   → Kort teeltseizoen (beperkt tot zomermaanden)")
                sections.append("")
        except:
            pass

    # Location data
    airport = property_data.get('custom_airport_distance_data')

    if airport:
        try:
            airport_data = eval(airport) if isinstance(airport, str) else airport
            distance_km = airport_data.get('distance_km', 'onbekend')
            airport_name = airport_data.get('airport_name', 'dichtstbijzijnde vliegveld')

            if distance_km != 'onbekend':
                sections.append(f"✈️ BEREIKBAARHEID:")
                sections.append(f"   • Afstand tot {airport_name}: {distance_km:.0f} km")
                drive_time = int(distance_km * 0.8)  # Rough estimate: ~45-60 km/h average
                sections.append(f"   • Geschatte rijtijd: ~{drive_time} minuten")

                if distance_km < 50:
                    sections.append(f"   → Uitstekende bereikbaarheid (ideaal voor gastenverblijf)")
                elif distance_km < 100:
                    sections.append(f"   → Goede bereikbaarheid (acceptabel voor toerisme)")
                elif distance_km < 150:
                    sections.append(f"   → Redelijke bereikbaarheid (factor voor gasten)")
                else:
                    sections.append(f"   → Beperkte bereikbaarheid (minder geschikt voor kort verblijf)")
                sections.append("")
        except:
            pass

    # Population data
    population = property_data.get('custom_population_density_data')

    if population:
        try:
            pop_data = eval(population) if isinstance(population, str) else population
            nearby_pop = pop_data.get('population_20km', 'onbekend')
            density = pop_data.get('density_category', 'onbekend')

            if nearby_pop != 'onbekend':
                sections.append(f"👥 LOKALE MARKT:")
                sections.append(f"   • Bevolking binnen 20km: ~{nearby_pop:,} inwoners")
                if density != 'onbekend':
                    sections.append(f"   • Dichtheid: {density}")

                if nearby_pop > 50000:
                    sections.append(f"   → Uitstekend afzetgebied (grote lokale markt voor producten)")
                elif nearby_pop > 20000:
                    sections.append(f"   → Goed afzetgebied (voldoende lokale vraag)")
                elif nearby_pop > 5000:
                    sections.append(f"   → Gemiddeld afzetgebied (beperkte lokale vraag)")
                else:
                    sections.append(f"   → Klein afzetgebied (afhankelijk van toerisme of transport)")
                sections.append("")
        except:
            pass

    # Overall custom score
    sections.append(f"📊 TOTALE OBJECTIEVE SCORE: {custom_score:.1f}/5.0")
    sections.append("")
    sections.append("⚠️ BELANGRIJK: Verwijs naar deze concrete cijfers in je analyse!")
    sections.append("   Bijvoorbeeld: 'Met 950mm neerslag per jaar...' of 'Gezien de 280 groeidagen...'")

    return "\n".join(sections)


# Test function
if __name__ == '__main__':
    # Test with sample property
    test_property = {
        'custom_score': 3.5,
        'custom_rainfall_data': "{'annual_rainfall_mm': 950, 'source': 'open-meteo'}",
        'custom_temperature_data': "{'growing_days': 280, 'avg_temp_c': 15.5}",
        'custom_airport_distance_data': "{'distance_km': 45, 'airport_name': 'Valencia Airport'}",
        'custom_population_density_data': "{'population_20km': 35000, 'density_category': 'suburban'}"
    }

    formatted = format_custom_data_for_prompt(test_property)
    print(formatted)
