import requests
from datetime import datetime
import urllib.parse
from flask import Flask

app = Flask(__name__)

def roman_to_arabic(value):
    roman_map = {
        'I': 1, 'V': 5, 'X': 10, 'L': 50,
        'C': 100, 'D': 500, 'M': 1000
    }
    if not value or not all(ch in roman_map for ch in value):
        return value
    total = 0
    prev_value = 0
    for ch in reversed(value):
        current = roman_map[ch]
        if current < prev_value:
            total -= current
        else:
            total += current
        prev_value = current
    return str(total)

def abbrevia_destinazione(dest):
    dest = dest.upper()
    dest = dest.replace("VITERBO PORTA FIORENTINA", "VITERBO P. F.")
    dest = dest.replace("VITERBO PORTA ROMANA", "VITERBO P. R.")
    return dest

@app.route("/")
def partenze():
    station_id = "S08327"  # Roma Balduina
    now = datetime.now()
    formatted = now.strftime("%a %b %d %Y %H:%M:%S +0200")
    encoded_date = urllib.parse.quote(formatted, safe="")
    
    url = f"http://www.viaggiatreno.it/infomobilita/resteasy/viaggiatreno/partenze/{station_id}/{encoded_date}"
    response = requests.get(url)
    
    if response.status_code != 200:
        table_rows = "<tr><td colspan='5'>ERRORE</td></tr>"
    else:
        data = response.json()
        table_rows = ""
        for treno in data[:8]:
            ora = datetime.fromtimestamp(treno['orarioPartenza']/1000).strftime('%H:%M').upper()
            destinazione = abbrevia_destinazione(treno.get('destinazione', 'SCONOSCIUTA'))
            categoria = treno.get('categoriaDescrizione', '').upper()
            numero = str(treno.get('numeroTreno', '')).upper()
            ritardo = treno.get('ritardo', 0)

            binario = treno.get('binarioEffettivoPartenzaDescrizione') or treno.get('binarioProgrammatoPartenzaDescrizione') or '-'
            binario = roman_to_arabic(binario)

            if ritardo > 0:
                stato = f"+{ritardo} MIN"
            elif ritardo < 0:
                stato = f"{ritardo} MIN"
            else:
                stato = " "

            table_rows += f"""
            <tr>
                <td>{ora}</td>
                <td>{categoria} {numero}</td>
                <td>{destinazione}</td>
                <td>{binario}</td>
                <td>{stato}</td>
            </tr>
            """

    html = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet">
    <style>
        html, body {{
            margin: 0;
            padding: 0;
            height: 100%;
            background-color: black;
            color: #FFD300;
            font-family: 'Share Tech Mono', monospace;
        }}
        table {{
            width: 98%;
            height: 95%;
            border-collapse: collapse;
            table-layout: auto;
            margin: auto;
        }}
        th, td {{
            padding: 0;
            text-align: center;
            font-size: clamp(10px, 2vw, 22px);
            white-space: nowrap;
        }}
        th {{
            font-weight: normal;
            border-bottom: 1px solid white;
            color: white;
            height: 1.8em;
        }}
        @media (max-width: 600px) {{
            th {{
                height: 2.2em;
            }}
        }}
        tr:nth-child(even) td {{
            background-color: #111;
        }}
        tbody tr {{
            height: calc(100% / 9);
        }}
        th:nth-child(1), td:nth-child(1) {{ width: 10%; }} /* ORARIO */
        th:nth-child(4), td:nth-child(4) {{ width: 8%; }}  /* BIN. */
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ORARIO</th>
                <th>TRENO</th>
                <th>DESTINAZIONE</th>
                <th>BIN.</th>
                <th>RITARDO</th>
            </tr>
        </thead>
        <tbody>
            {table_rows}
        </tbody>
    </table>
</body>
</html>"""
    return html

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9999)
