import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# Data: Spanish property prices per m² (asking/purchase prices, 2025-2026)
# Sources: INE, Engel Völkers Q2 2026, Indomio June 2026, GlobalPropertyGuide

regions = [
    ("Madrid", 3902),
    ("Baleares", 5073),
    ("Barcelona", 3083),
    ("Cataluña", 2837),
    ("Islas Canarias", 2755),
    ("País Vasco", 2364),
    ("Andalucía", 3010),
    ("Cantabria", 2074),
    ("Navarra", 1960),
    ("Alicante", 1903),
    ("C. Valenciana", 1832),
    ("Sevilla", 1780),
    ("Ceuta/Melilla", 1743),
    ("Asturias", 1554),
    ("La Rioja", 1540),
    ("Galicia", 1499),
    ("Aragón", 1138),
    ("Extremadura", 1152),
    ("C. Castilla", 1409),
    ("C. Castilla-La Mancha", 1117),
]

# Sort by price descending
regions.sort(key=lambda x: x[1], reverse=True)

labels = [r[0] for r in regions]
prices = [r[1] for r in regions]

# Colors: gradient from dark red (expensive) to dark green (cheap)
import numpy as np
norm = plt.Normalize(min(prices), max(prices))
cmap = plt.cm.RdYlGn_r  # reversed: red=high, green=low
colors = [cmap(norm(p)) for p in prices]

fig, ax = plt.subplots(figsize=(16, 10))

bars = ax.barh(labels, prices, color=colors, edgecolor='#333333', linewidth=0.8, height=0.7)

# Add value labels on bars
for bar, price in zip(bars, prices):
    ax.text(bar.get_width() + 40, bar.get_y() + bar.get_height()/2,
            f'€{price:,.0f}/m²', va='center', fontsize=9, fontweight='bold', color='#222222')

ax.set_xlabel('Price per Square Meter (€)', fontsize=13, fontweight='bold', color='#333333')
ax.set_title('Spanish Property Prices per m² by Region\n(Average Asking/Purchase Prices, 2025–2026)',
             fontsize=16, fontweight='bold', color='#1a1a2e', pad=20)

ax.set_xlim(0, max(prices) * 1.18)
ax.invert_yaxis()

# Remove top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.tick_params(left=False, labelsize=10)

# Add a subtle grid
ax.xaxis.grid(True, linestyle='--', alpha=0.3)
ax.set_axisbelow(True)

# Add national average line
national_avg = sum(prices) / len(prices)
ax.axvline(x=national_avg, color='black', linestyle='--', linewidth=1.5, alpha=0.7, label=f'National Avg: €{national_avg:,.0f}/m²')
ax.legend(loc='lower right', fontsize=10, framealpha=0.9)

# Add source note
fig.text(0.02, 0.02, 'Sources: INE (Q4 2025), Engel Völkers (Q2 2026), Indomio (June 2026), GlobalPropertyGuide\nData reflects average asking/purchase prices for residential property for sale.',
         fontsize=8, color='#666666', style='italic')

plt.tight_layout(rect=[0.02, 0.06, 1, 0.94])
plt.savefig('artifacts/spain_property_prices_chart.png', dpi=200, bbox_inches='tight', facecolor='white')
plt.savefig('artifacts/spain_property_prices_chart.svg', bbox_inches='tight', facecolor='white')
print("Chart saved as PNG and SVG")
