import tkinter as tk
from tkinter import ttk
import math

class Abacus:
    def __init__(self, root):
        self.root = root
        self.root.title("Interactive Abacus")
        self.root.geometry("800x600")
        self.root.configure(bg='#8B4513')
        
        # Abacus configuration
        self.num_columns = 10  # Number of digit columns
        self.heaven_beads_per_column = 2  # Upper beads (worth 5 each)
        self.earth_beads_per_column = 5   # Lower beads (worth 1 each)
        
        # Visual settings
        self.bead_radius = 15
        self.column_width = 70
        self.heaven_section_height = 120
        self.earth_section_height = 180
        self.crossbar_height = 10
        
        # Data structure to track bead positions
        # True = bead is "active" (counting), False = "inactive"
        self.heaven_beads = [[False] * self.heaven_beads_per_column for _ in range(self.num_columns)]
        self.earth_beads = [[False] * self.earth_beads_per_column for _ in range(self.num_columns)]
        
        self.setup_ui()
        self.draw_abacus()
        self.update_display()
    
    def setup_ui(self):
        # Main frame
        self.main_frame = tk.Frame(self.root, bg='#8B4513')
        self.main_frame.pack(expand=True, fill='both', padx=20, pady=20)
        
        # Canvas for abacus
        canvas_width = self.num_columns * self.column_width + 40
        canvas_height = self.heaven_section_height + self.earth_section_height + self.crossbar_height + 60
        
        self.canvas = tk.Canvas(
            self.main_frame,
            width=canvas_width,
            height=canvas_height,
            bg='#D2691E',
            highlightthickness=2,
            highlightbackground='#654321'
        )
        self.canvas.pack(pady=10)
        
        # Value display
        self.value_label = tk.Label(
            self.main_frame,
            text="Value: 0",
            font=('Arial', 18, 'bold'),
            bg='#8B4513',
            fg='white'
        )
        self.value_label.pack(pady=10)
        
        # Reset button
        self.reset_button = tk.Button(
            self.main_frame,
            text="Reset Abacus",
            command=self.reset_abacus,
            font=('Arial', 12),
            bg='#CD853F',
            fg='black'
        )
        self.reset_button.pack(pady=5)
        
        # Instructions
        instructions = tk.Label(
            self.main_frame,
            text="Click on beads to slide them. Heaven beads (top) = 5, Earth beads (bottom) = 1",
            font=('Arial', 10),
            bg='#8B4513',
            fg='lightgray',
            wraplength=600
        )
        instructions.pack(pady=5)
    
    def draw_abacus(self):
        self.canvas.delete("all")
        
        # Draw frame
        frame_margin = 20
        frame_width = self.num_columns * self.column_width
        frame_height = self.heaven_section_height + self.earth_section_height + self.crossbar_height
        
        self.canvas.create_rectangle(
            frame_margin, frame_margin,
            frame_margin + frame_width, frame_margin + frame_height,
            fill='#8B4513', outline='#654321', width=3
        )
        
        # Draw crossbar (separates heaven and earth beads)
        crossbar_y = frame_margin + self.heaven_section_height
        self.canvas.create_rectangle(
            frame_margin, crossbar_y,
            frame_margin + frame_width, crossbar_y + self.crossbar_height,
            fill='#654321', outline='#654321'
        )
        
        # Draw vertical rods and beads for each column
        for col in range(self.num_columns):
            self.draw_column(col, frame_margin)
        
        # Draw column labels (place values)
        for col in range(self.num_columns):
            x = frame_margin + col * self.column_width + self.column_width // 2
            place_value = 10 ** (self.num_columns - 1 - col)
            if place_value >= 1000000:
                label = f"{place_value // 1000000}M"
            elif place_value >= 1000:
                label = f"{place_value // 1000}K"
            else:
                label = str(place_value)
            
            self.canvas.create_text(
                x, frame_margin - 10,
                text=label, font=('Arial', 8), fill='black'
            )
    
    def draw_column(self, col, frame_margin):
        # Calculate column position
        col_x = frame_margin + col * self.column_width + self.column_width // 2
        
        # Draw vertical rod
        rod_top = frame_margin + 5
        rod_bottom = frame_margin + self.heaven_section_height + self.earth_section_height + self.crossbar_height - 5
        self.canvas.create_line(
            col_x, rod_top, col_x, rod_bottom,
            fill='#2F4F4F', width=4
        )
        
        # Draw heaven beads (upper section)
        heaven_start_y = frame_margin + 10
        for bead_idx in range(self.heaven_beads_per_column):
            if self.heaven_beads[col][bead_idx]:  # Active (counting)
                y = heaven_start_y + self.heaven_section_height - 40 - bead_idx * 35
            else:  # Inactive
                y = heaven_start_y + bead_idx * 35
            
            bead_id = self.draw_bead(col_x, y, 'heaven', col, bead_idx)
        
        # Draw earth beads (lower section)
        earth_start_y = frame_margin + self.heaven_section_height + self.crossbar_height + 10
        for bead_idx in range(self.earth_beads_per_column):
            if self.earth_beads[col][bead_idx]:  # Active (counting)
                y = earth_start_y + bead_idx * 32
            else:  # Inactive
                y = earth_start_y + self.earth_section_height - 50 - bead_idx * 32
            
            bead_id = self.draw_bead(col_x, y, 'earth', col, bead_idx)
    
    def draw_bead(self, x, y, bead_type, col, bead_idx):
        # Choose colors based on type and state
        if bead_type == 'heaven':
            is_active = self.heaven_beads[col][bead_idx]
            color = '#FFD700' if is_active else '#FFA500'  # Gold when active, orange when inactive
        else:  # earth
            is_active = self.earth_beads[col][bead_idx]
            color = '#32CD32' if is_active else '#90EE90'  # Green when active, light green when inactive
        
        # Draw bead
        bead_id = self.canvas.create_oval(
            x - self.bead_radius, y - self.bead_radius,
            x + self.bead_radius, y + self.bead_radius,
            fill=color, outline='#654321', width=2,
            tags=f"{bead_type}_{col}_{bead_idx}"
        )
        
        # Bind click event
        self.canvas.tag_bind(bead_id, "<Button-1>", 
                           lambda e, t=bead_type, c=col, b=bead_idx: self.toggle_bead(t, c, b))
        
        return bead_id
    
    def toggle_bead(self, bead_type, col, bead_idx):
        """Toggle a bead between active and inactive states"""
        if bead_type == 'heaven':
            # For heaven beads, we need to maintain proper order
            current_state = self.heaven_beads[col][bead_idx]
            if current_state:  # Currently active, deactivate this and all above
                for i in range(bead_idx, self.heaven_beads_per_column):
                    self.heaven_beads[col][i] = False
            else:  # Currently inactive, activate this and all below
                for i in range(bead_idx + 1):
                    self.heaven_beads[col][i] = True
        else:  # earth beads
            # For earth beads, maintain proper order
            current_state = self.earth_beads[col][bead_idx]
            if current_state:  # Currently active, deactivate this and all above
                for i in range(bead_idx, self.earth_beads_per_column):
                    self.earth_beads[col][i] = False
            else:  # Currently inactive, activate this and all below
                for i in range(bead_idx + 1):
                    self.earth_beads[col][i] = True
        
        # Redraw and update display
        self.draw_abacus()
        self.update_display()
    
    def calculate_value(self):
        """Calculate the total value represented by the abacus"""
        total = 0
        
        for col in range(self.num_columns):
            place_value = 10 ** (self.num_columns - 1 - col)
            
            # Count active heaven beads (worth 5 each)
            heaven_count = sum(1 for bead in self.heaven_beads[col] if bead)
            
            # Count active earth beads (worth 1 each)
            earth_count = sum(1 for bead in self.earth_beads[col] if bead)
            
            # Add to total
            digit_value = (heaven_count * 5 + earth_count) * place_value
            total += digit_value
        
        return total
    
    def update_display(self):
        """Update the value display"""
        value = self.calculate_value()
        self.value_label.config(text=f"Value: {value:,}")
    
    def reset_abacus(self):
        """Reset all beads to inactive state"""
        for col in range(self.num_columns):
            for bead_idx in range(self.heaven_beads_per_column):
                self.heaven_beads[col][bead_idx] = False
            for bead_idx in range(self.earth_beads_per_column):
                self.earth_beads[col][bead_idx] = False
        
        self.draw_abacus()
        self.update_display()

def main():
    root = tk.Tk()
    abacus = Abacus(root)
    root.mainloop()

if __name__ == "__main__":
    main()