# -*- coding: utf-8 -*-
"""
Created on Fri Oct  3 12:42:55 2025

@author: Moritz Romeike
"""
# ------------------------------------------------------------------------
# Programmcode 19 (Python): Heatmap der Lieferantenanteile (mit echarts)
# ------------------------------------------------------------------------


import os, json, webbrowser

# ------------------ Daten ------------------
lieferanten_anteile = [
    12.5, 10.3, 9.8, 8.5, 7.6, 6.9, 6.5, 6.2, 5.8, 5.2,
    4.9, 4.6, 4.2, 3.9, 3.7, 3.5, 3.3, 3.1, 2.9, 2.7,
    2.5, 2.3, 2.1, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3,
    1.2, 1.1, 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3,
    0.3, 0.3, 0.3, 0.2, 0.2, 0.2, 0.1, 0.1, 0.1, 0.1
]
lieferanten = [f"Lieferant {i+1}" for i in range(len(lieferanten_anteile))]
y_categories = ["Marktanteil (%)"]
data_triplets = [[i, 0, v] for i, v in enumerate(lieferanten_anteile)]
min_value, max_value = min(lieferanten_anteile), max(lieferanten_anteile)

# ------------------ Dateien ------------------
html_path = "heatmap_lieferanten_offline.html"
echarts_js = "echarts.min.js"  # muss im selben Ordner liegen

# ------------------ Becharts.min.js lokal sicherstellen ------------------
def ensure_echarts_js(local_filename: str) -> bool:
    if os.path.exists(local_filename) and os.path.getsize(local_filename) > 100_000:
        return True  # plausibel vorhanden
    # Optionaler Download (falls Internet erlaubt). Überspringt still, wenn requests fehlt.
    urls = [
        "https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js",
        "https://unpkg.com/echarts@5/dist/echarts.min.js",
    ]
    try:
        import requests
        for u in urls:
            try:
                print(f"Versuche Download: {u}")
                r = requests.get(u, timeout=10)
                if r.ok and r.text and len(r.content) > 100_000:
                    with open(local_filename, "wb") as f:
                        f.write(r.content)
                    print(f"✔ echarts.min.js gespeichert: {os.path.abspath(local_filename)}")
                    return True
            except Exception:
                pass
        print("⚠ echarts.min.js konnte nicht heruntergeladen werden.")
    except Exception:
        print("Hinweis: 'requests' nicht verfügbar; Download wird übersprungen.")
    return os.path.exists(local_filename) and os.path.getsize(local_filename) > 100_000

have_local_js = ensure_echarts_js(echarts_js)

# ------------------ HTML schreiben ------------------
option = {
    "title": {"text": "Heatmap der Marktanteile der Lieferanten", "subtext": "Inntal AG", "left": "center", "top": "2%"},
    "grid": {"top": "16%", "bottom": "22%", "left": "6%", "right": "3%"},
    "tooltip": {
        "trigger": "item",
        "formatter": "function (p){ return p.name + '<br/>Marktanteil: ' + p.value[2].toFixed(1) + ' %'; }"
    },
    "xAxis": {
        "type": "category",
        "name": "Lieferanten",
        "nameGap": 28,
        "axisLabel": {"rotate": 60, "fontSize": 10, "margin": 12},
        "data": lieferanten
    },
    "yAxis": {
        "type": "category",
        "data": y_categories,
        "axisLabel": {"show": False},
        "axisLine": {"show": False},
        "axisTick": {"show": False},
        "splitLine": {"show": False}
    },
    "visualMap": {
        "min": min_value, "max": max_value, "orient": "horizontal",
        "left": "center", "bottom": "2%",
        "itemWidth": 18, "itemHeight": 120,
        "inRange": {"color": ["green","orange","red"]},
        "text": ["hoch (%)","niedrig (%)"]
    },
    "series": [{
        "name": "Marktanteil",
        "type": "heatmap",
        "data": data_triplets,
        "label": {"show": False},
        "emphasis": {"itemStyle": {"shadowBlur": 10, "shadowColor": "rgba(0,0,0,0.4)"}}
    }]
}

html = f"""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>ECharts Heatmap – Offline</title>
<style>
  html, body {{ height:100%; margin:0; }}
  #main {{ width: 1200px; height: 420px; margin: 16px auto 90px auto; }}
</style>
<script src="{echarts_js}"></script>
</head>
<body>
<div id="main"></div>
<script>
(function(){{
  if (typeof echarts === 'undefined') {{
    document.getElementById('main').innerHTML =
      "<div style='color:red;font-family:monospace'>Fehler: echarts.min.js wurde nicht geladen.<br>"+
      "Lege die Datei <b>{echarts_js}</b> in denselben Ordner wie diese HTML.</div>";
    return;
  }}
  var chart = echarts.init(document.getElementById('main'));
  var option = {json.dumps(option, ensure_ascii=False)};
  // Tooltip-Formatter als Funktion einsetzen:
  option.tooltip.formatter = {option['tooltip']['formatter']};
  chart.setOption(option);
  window.addEventListener('resize', function(){{ chart.resize(); }});
}})();
</script>
</body>
</html>
"""

with open(html_path, "w", encoding="utf-8") as f:
    f.write(html)

print("HTML gespeichert:", os.path.abspath(html_path))
if not have_local_js:
    print("\n⚠ Wichtiger Hinweis:")
    print(f"- Lege die Datei 'echarts.min.js' in denselben Ordner wie '{html_path}'.")
    print("- Downloadquelle:")
    print("  https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js  (Datei speichern als echarts.min.js)")
    print("  Danach HTML neu öffnen.")
else:
    # automatisch im Browser öffnen
    webbrowser.open(f"file://{os.path.abspath(html_path)}", new=2)

# ------------------------------------------------------------------------
