import network
import urequests
import time
import os
from machine import Pin, PWM, I2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from secrets import WIFI_SSID, WIFI_PASSWORD, OPENROUTER_API_KEY

# === Pins ===
LED1 = Pin(6, Pin.OUT)
LED2 = Pin(8, Pin.OUT)
BUZZER = PWM(Pin(10))
BUTTON = Pin(15, Pin.IN, Pin.PULL_UP)

# === LCD on I2C0 — SDA: GP4, SCL: GP1 ===
i2c = I2C(0, sda=Pin(4), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
lcd.backlight_on()

# === Sound ===
def play_victory_tune():
    melody = [(880, 0.2), (988, 0.2), (1046, 0.4)]
    for freq, duration in melody:
        BUZZER.freq(freq)
        BUZZER.duty_u16(30000)
        time.sleep(duration)
    BUZZER.duty_u16(0)

# === Wi-Fi Connect ===
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    for _ in range(20):
        if wlan.isconnected():
            return True
        time.sleep(0.5)
    return False

# === Offline mode ===
def offline_mode():
    LED1.value(1)
    LED2.value(1)
    lcd.clear()
    lcd.putstr("Wi-Fi's off.")
    lcd.move_to(0, 1)
    lcd.putstr("Fix it, genius.")
    while True:
        time.sleep(1)

# === Load insult history ===
def load_insults():
    try:
        with open("insults.txt", "r") as f:
            return [line.strip() for line in f.readlines()]
    except:
        return []

# === Save new insult ===
def save_insult(insult):
    with open("insults.txt", "a") as f:
        f.write(insult + "\n")

# === Ask OpenRouter for new insult ===
def get_insult():
    previous = load_insults()
    prompt = (
        "Give me a very short, rude insult under 32 characters. "
        "Do NOT include quotes or explanation. "
        "That is not similar to any of these: "
        + ", ".join(previous[-10:])
    )

    url = "https://openrouter.ai/api/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://yourdomain.com",
        "X-Title": "pico-insult-bot"
    }
    body = {
        "model": "mistralai/mistral-7b-instruct",
        "messages": [{"role": "user", "content": prompt}]
    }

    try:
        r = urequests.post(url, headers=headers, json=body)
        result = r.json()
        print("API response:", result)
        text = result["choices"][0]["message"]["content"]
        cleaned = text.strip().strip('"').split("\n")[0][:32]
        save_insult(cleaned)
        return cleaned
    except Exception as e:
        print("Error in get_insult():", e)
        return "You even fail at failing."

# === Display helper ===
def display(text):
    lcd.clear()
    lcd.move_to(0, 0)
    lcd.putstr(text[:16])
    lcd.move_to(0, 1)
    lcd.putstr(text[16:32])

# === Acknowledge ===
def acknowledge():
    LED1.value(1)
    LED2.value(1)
    BUZZER.duty_u16(0)
    lcd.clear()
    lcd.putstr("I know, I'm")
    lcd.move_to(0, 1)
    lcd.putstr("always right.")
    play_victory_tune()
    time.sleep(15)
    main()

# === Annoy mode ===
def annoy_loop(insult):
    display(insult)
    while BUTTON.value():
        LED1.toggle()
        LED2.toggle()
        BUZZER.freq(1500)
        BUZZER.duty_u16(30000)
        time.sleep(0.25)
        BUZZER.duty_u16(0)
        time.sleep(0.25)
    acknowledge()

# === Main ===
def main():
    lcd.clear()
    lcd.putstr("Connecting WiFi")
    LED1.value(1)
    LED2.value(1)
    if not connect_wifi():
        offline_mode()

    lcd.clear()
    lcd.putstr("Fetching insult")
    time.sleep(0.5)
    insult = get_insult() or "You're not even Pico-worthy."
    annoy_loop(insult)

main()
