#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageFont
import datetime
import math
import subprocess
import re
import os
import time

TIMESTAMP_FILE = "/tmp/weather.timestamp"
ICON_FILE = "/tmp/weather.icon"
WEATHER_INTERVAL = 60 * 60  
FONT_PATH = "/home/richard/.fonts/NotoEmoji-Regular.ttf"

def get_weather_icon():
    now = time.time()
    last_call = 0

    known_new_moon = 947182440
    synodic_month = 29.530588853
    now = int(time.time())
    days_since_new_moon = (now - known_new_moon) / 86400.0
    moon_age = math.fmod(days_since_new_moon, synodic_month)
    phase_index = int((moon_age / synodic_month) * 8 + 0.5) % 8
    moon_symbols = [
        "🌑",
        "🌒",
        "🌓",
        "🌔",
        "🌕",
        "🌖",
        "🌗",
        "🌘",
    ]

    moon_phase = moon_symbols[phase_index]
    
    try:
        with open(TIMESTAMP_FILE, "r", encoding="utf-8") as file:
            last_call = float(file.read().strip())
    except (FileNotFoundError, ValueError, OSError):
        pass

    if now - last_call < WEATHER_INTERVAL:
        try:
            with open(ICON_FILE, "r", encoding="utf-8") as file:
                return file.read().strip(), moon_phase
        except (FileNotFoundError, OSError):
            pass
        
    ansiweather = os.path.expanduser(
        "~/.prog/ansiweather/ansiweather"
    )

    result = subprocess.run(
        [
            ansiweather,
            "-l", "Poprad",
            "-a", "false",
            "-i", "false",
            "-w", "false",
            "-s", "true",
        ],
        capture_output=True,
        text=True,
        check=True
    )

    match = re.search(
        r"°C\s+([^ ]+)\s+-\s+Humidity",
        result.stdout
    )

    if not match:
        raise RuntimeError("Could not extract weather icon")

    weather_icon = match.group(1).replace("\ufe0f", "")

    print("OpenWeather was contacted")

    with open(ICON_FILE, "w", encoding="utf-8") as file:
        file.write(weather_icon)

    with open(TIMESTAMP_FILE, "w", encoding="utf-8") as file:
        file.write(str(int(now)))

    return weather_icon, moon_phase




img = Image.new('RGBA', (300, 300), (0, 0, 0, 0))  
draw = ImageDraw.Draw(img)

center = (150, 150)
radius = 140
draw.ellipse((center[0]-radius, center[1]-radius, center[0]+radius,
              center[1]+radius), outline=(64, 64, 64), width=3)

    
for i in range(12):
    angle = math.radians(i * 30 - 90)  
    x1 = center[0] + (radius - 15) * math.cos(angle)
    y1 = center[1] + (radius - 15) * math.sin(angle)
    x2 = center[0] + radius * math.cos(angle)
    y2 = center[1] + radius * math.sin(angle)
    draw.line([(x1, y1), (x2, y2)], fill="#404040", width=3)


weather_icon, moon_phase = get_weather_icon()

draw.text(
    (center[0], 72),
    moon_phase,
    font=ImageFont.truetype(FONT_PATH, 68),
    anchor="mm",
    fill="#606060"
)

draw.text(
    (center[0], 225),
    weather_icon,
    font=ImageFont.truetype(FONT_PATH, 68),
    anchor="mm",
    fill="#404040"
)




now = datetime.datetime.now()
hours, minutes = now.hour % 12, now.minute

hour_angle = math.radians((hours * 30) + (minutes * 0.5) - 90)  
hour_length = radius * 0.5
hour_x = center[0] + hour_length * math.cos(hour_angle)
hour_y = center[1] + hour_length * math.sin(hour_angle)
draw.line([center, (hour_x, hour_y)], fill='red', width=18)

minute_angle = math.radians(minutes * 6 - 90)
minute_length = radius * 0.8
minute_x = center[0] + minute_length * math.cos(minute_angle)
minute_y = center[1] + minute_length * math.sin(minute_angle)
draw.line([center, (minute_x, minute_y)], fill='black', width=8)

draw.ellipse((center[0]-5, center[1]-5, center[0]+5, center[1]+5),
             fill="#404040")


img.save("/tmp/analog_clock.png")
print('/tmp/analog_clock.png')
