#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
import csv
import chess
import time
import logging
from waveshare_epd import epd7in5_V2
from PIL import Image, ImageDraw, ImageFont
from Adafruit_IO import Client, MQTTClient

# Configuration
CSV_FILE = 'chess_puzzles.csv'
ADAFRUIT_IO_KEY = 'your_adafruit_io_key'
ADAFRUIT_IO_USERNAME = 'your_username'
MOVE_FEED = 'chess-moves'
FEEDBACK_FEED = 'puzzle-feedback'

# Display setup
picdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pic')
libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')
sys.path.append(libdir)

epd = epd7in5_V2.EPD()
font = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
cell_size = 50  # Adjust based on your display size

# Global variables
puzzles = []
current_puzzle = None
current_solution = []
current_step = 0

def load_puzzles():
    """Load puzzles from CSV file"""
    global puzzles
    with open(CSV_FILE, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            puzzles.append({
                'fen': row['FEN'],
                'solution': row['Moves'].split(),
                'id': row['PuzzleId'],
                'rating': row['Rating']
            })

def draw_chess_board(fen):
    """Draw chess board on e-ink display"""
    board = chess.Board(fen)
    image = Image.new('1', (epd.width, epd.height), 255)
    draw = ImageDraw.Draw(image)
    
    # Draw chessboard grid
    for rank in range(8):
        for file in range(8):
            x = 10 + file * cell_size
            y = 10 + rank * cell_size
            color = 0 if (rank + file) % 2 == 0 else 255
            draw.rectangle([x, y, x+cell_size, y+cell_size], fill=color)
            
            # Draw pieces
            square = chess.square(file, 7-rank)
            piece = board.piece_at(square)
            if piece:
                text = piece.symbol()
                if piece.color == chess.WHITE:
                    text = text.upper()
                else:
                    text = text.lower()
                draw.text(
                    (x + cell_size//4, y + cell_size//4),
                    text,
                    font=font,
                    fill=255-color
                )
    
    # Draw puzzle info
    draw.text((400, 10), f"Puzzle: {current_puzzle['id']}", font=font, fill=0)
    draw.text((400, 40), f"Rating: {current_puzzle['rating']}", font=font, fill=0)
    
    epd.init()
    epd.display(epd.getbuffer(image))

def handle_move(client, feed_id, payload):
    """Process moves from Adafruit.io"""
    global current_step
    try:
        if payload.lower() == current_solution[current_step]:
            current_step += 1
            if current_step >= len(current_solution):
                aio.send(FEEDBACK_FEED, "Correct! Puzzle solved!")
                load_next_puzzle()
            else:
                aio.send(FEEDBACK_FEED, f"Correct! Next move: {current_step+1}/{len(current_solution)}")
        else:
            aio.send(FEEDBACK_FEED, "Incorrect move! Try again")
    except:
        aio.send(FEEDBACK_FEED, "Invalid move format")

def load_next_puzzle():
    """Load and display next puzzle"""
    global current_puzzle, current_solution, current_step
    if puzzles:
        current_puzzle = puzzles.pop(0)
        current_solution = current_puzzle['solution']
        current_step = 0
        draw_chess_board(current_puzzle['fen'])
        aio.send(FEEDBACK_FEED, f"New puzzle loaded: {current_puzzle['id']}")
    else:
        aio.send(FEEDBACK_FEED, "No more puzzles!")

def main():
    # Initialize display
    epd.init()
    epd.Clear()
    
    # Load puzzles
    load_puzzles()
    
    # Connect to Adafruit IO
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    mqtt = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    mqtt.on_message = handle_move
    mqtt.connect()
    mqtt.subscribe(MOVE_FEED)
    
    # Load first puzzle
    load_next_puzzle()
    
    # Main loop
    while True:
        mqtt.loop()
        time.sleep(1)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        epd.sleep()
        sys.exit()