#!/usr/bin/env python3
"""
Elevator state visualizer.

Usage:
    python elevator.py states.txt
    python elevator.py states.txt --floors 5

If no input file is supplied, a file picker is opened. If that is unavailable,
the program looks for "states.txt" in the current directory.

Input format:
    State 0:
    call(2) o(open)
    o(close)

    State 1:
    o(move(up)) call(4)

Each State block describes the predicates that are true in that state.
The elevator starts at floor 0 with its doors open. Movement and door
predicates update the elevator from one state to the next; call(F) predicates
are displayed exactly as listed in each state (they are not accumulated).
"""

from __future__ import annotations

import argparse
import re
import sys
from dataclasses import dataclass
from pathlib import Path

import pygame


# Extracts atoms even when several appear on the same line.
STATE_RE = re.compile(r"^\s*State\s+(\d+)\s*:\s*$", re.IGNORECASE)
ATOM_RE = re.compile(
    r"call\s*\(\s*(\d+)\s*\)"
    r"|o\s*\(\s*move\s*\(\s*(up|down)\s*\)\s*\)"
    r"|o\s*\(\s*(open|close)\s*\)",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class Snapshot:
    state_number: int
    floor: int
    doors_open: bool
    calls: tuple[int, ...]
    actions: tuple[str, ...]


def parse_states(path: Path, floors: int) -> list[Snapshot]:
    """Parse the trace and calculate the elevator snapshot for every state."""
    try:
        content = path.read_text(encoding="utf-8")
    except OSError as exc:
        raise ValueError(f"Could not read '{path}': {exc}") from exc

    blocks: list[tuple[int, list[str]]] = []
    current_number: int | None = None
    current_lines: list[str] = []

    for line in content.splitlines():
        match = STATE_RE.match(line)
        if match:
            if current_number is not None:
                blocks.append((current_number, current_lines))
            current_number = int(match.group(1))
            current_lines = []
        elif current_number is not None:
            current_lines.append(line)
        elif line.strip() and not line.lstrip().startswith(("#", "//")) and line!="SATISFIABLE":
            raise ValueError(
                "Found content before the first 'State i:' header: "
                + line.strip()
            )

    if current_number is not None:
        blocks.append((current_number, current_lines))

    if not blocks:
        raise ValueError("No states found. Expected headers such as 'State 0:'.")

    floor = 0
    doors_open = True
    snapshots: list[Snapshot] = []

    for state_number, lines in blocks:
        calls: set[int] = set()
        actions: list[str] = []

        for line in lines:
            # Ignore comments, then find every supported atom on the line.
            line = re.split(r"#|//", line, maxsplit=1)[0]
            for atom in ATOM_RE.finditer(line):
                call_floor, direction, door_action = atom.groups()
                if call_floor is not None:
                    requested_floor = int(call_floor)
                    if not 0 <= requested_floor < floors:
                        raise ValueError(
                            f"State {state_number}: call({requested_floor}) "
                            f"is outside the configured floors 0..{floors - 1}."
                        )
                    calls.add(requested_floor)
                elif direction is not None:
                    direction = direction.lower()
                    floor += 1 if direction == "up" else -1
                    if not 0 <= floor < floors:
                        raise ValueError(
                            f"State {state_number}: move({direction}) would "
                            f"take the elevator outside floors 0..{floors - 1}."
                        )
                    actions.append(f"move({direction})")
                elif door_action is not None:
                    door_action = door_action.lower()
                    doors_open = door_action == "open"
                    actions.append(door_action)

        snapshots.append(
            Snapshot(
                state_number=state_number,
                floor=floor,
                doors_open=doors_open,
                calls=tuple(sorted(calls)),
                actions=tuple(actions),
            )
        )

    return snapshots


class ElevatorViewer:
    WIDTH = 900
    HEIGHT = 680
    FPS = 60

    BG = (24, 29, 39)
    PANEL = (36, 43, 57)
    PANEL_LIGHT = (49, 58, 75)
    TEXT = (238, 242, 248)
    MUTED = (164, 176, 194)
    ACCENT = (83, 170, 255)
    GREEN = (82, 205, 145)
    RED = (238, 103, 103)
    YELLOW = (245, 194, 85)
    LINE = (83, 96, 118)

    def __init__(self, snapshots: list[Snapshot], floors: int, source: Path):
        pygame.init()
        pygame.display.set_caption("Elevator State Visualizer")
        self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("arial", 22)
        self.small = pygame.font.SysFont("arial", 17)
        self.title_font = pygame.font.SysFont("arial", 29, bold=True)
        self.big_font = pygame.font.SysFont("arial", 25, bold=True)

        self.snapshots = snapshots
        self.floors = floors
        self.source = source
        self.index = 0
        self.buttons = self._make_buttons()

    def _make_buttons(self):
        labels = [
            ("|<", "first"),
            ("<", "previous"),
            (">", "next"),
            (">|", "last"),
        ]
        button_w, button_h, gap = 112, 48, 15
        total = len(labels) * button_w + (len(labels) - 1) * gap
        start_x = (self.WIDTH - total) // 2
        y = 605
        return [
            (pygame.Rect(start_x + i * (button_w + gap), y, button_w, button_h),
             label, action)
            for i, (label, action) in enumerate(labels)
        ]

    @property
    def current(self) -> Snapshot:
        return self.snapshots[self.index]

    def _text(self, text, x, y, color=None, font=None):
        surface = (font or self.font).render(
            str(text), True, color or self.TEXT
        )
        self.screen.blit(surface, (x, y))
        return surface.get_width()

    def _center_text(self, text, center_x, y, color=None, font=None):
        surface = (font or self.font).render(
            str(text), True, color or self.TEXT
        )
        self.screen.blit(surface, (center_x - surface.get_width() // 2, y))

    def draw(self):
        self.screen.fill(self.BG)
        self._text("Elevator State Visualizer", 35, 24, font=self.title_font)
        self._text(
            f"File: {self.source.name}     Floors: 0–{self.floors - 1}",
            37, 65, self.MUTED, self.small
        )

        self._draw_building()
        self._draw_status()
        self._draw_timeline()
        self._draw_buttons()

        pygame.display.flip()

    def _draw_building(self):
        # Building / shaft panel.
        panel = pygame.Rect(35, 110, 390, 465)
        pygame.draw.rect(self.screen, self.PANEL, panel, border_radius=16)
        self._text("ELEVATOR SHAFT", 58, 128, self.MUTED, self.small)

        shaft_x, shaft_y, shaft_w, shaft_h = 155, 174, 180, 350
        pygame.draw.rect(
            self.screen, (19, 23, 32),
            (shaft_x, shaft_y, shaft_w, shaft_h), border_radius=8
        )

        floor_h = shaft_h / self.floors
        for floor in range(self.floors):
            y = shaft_y + shaft_h - (floor + 1) * floor_h
            pygame.draw.line(
                self.screen, self.LINE,
                (shaft_x, int(y + floor_h)),
                (shaft_x + shaft_w, int(y + floor_h)), 2
            )
            if floor in self.current.calls:
               pygame.draw.circle(
                   self.screen, self.RED, 
                   (shaft_x+shaft_w+10, int(y + floor_h/2)), 7
               )
               self._text(
                    f"CALL", shaft_x+shaft_w+25, int(y + floor_h/2-12),
                    self.RED
               )


            self._text(
                f"{floor}", shaft_x - 30, int(y + floor_h / 2 - 11),
                self.MUTED
            )
            
        # Car is centered in its current floor.
        car_h = min(55, floor_h - 8)
        car_y = shaft_y + shaft_h - (self.current.floor + 1) * floor_h
        car_y += (floor_h - car_h) / 2
        car = pygame.Rect(shaft_x + 18, int(car_y), shaft_w - 36, int(car_h))
        pygame.draw.rect(self.screen, self.PANEL_LIGHT, car, border_radius=7)
        pygame.draw.rect(self.screen, self.ACCENT, car, 2, border_radius=7)

        # Doors: open means two panels slid to the sides.
        door_color = self.GREEN if self.current.doors_open else self.YELLOW
        if self.current.doors_open:
            left = pygame.Rect(car.left + 5, car.top + 5, 12, car.height - 10)
            right = pygame.Rect(car.right - 17, car.top + 5, 12, car.height - 10)
            pygame.draw.rect(self.screen, door_color, left, border_radius=2)
            pygame.draw.rect(self.screen, door_color, right, border_radius=2)
            self._center_text(
                "OPEN", car.centerx, car.centery - 10, self.TEXT, self.small
            )
        else:
            doors = pygame.Rect(
                car.left + 5, car.top + 5, car.width - 10, car.height - 10
            )
            pygame.draw.rect(self.screen, door_color, doors, 2, border_radius=2)
            pygame.draw.line(
                self.screen, door_color,
                (doors.centerx, doors.top), (doors.centerx, doors.bottom), 2
            )

        self._center_text(
            f"Floor {self.current.floor}",
            panel.centerx, 540, self.TEXT, self.big_font
        )

    def _draw_status(self):
        panel = pygame.Rect(450, 110, 415, 465)
        pygame.draw.rect(self.screen, self.PANEL, panel, border_radius=16)

        self._text("CURRENT STATE", 475, 132, self.MUTED, self.small)
        self._text(
            f"State {self.current.state_number}",
            475, 162, font=self.title_font
        )

        self._text("DOORS", 475, 225, self.MUTED, self.small)
        door_label = "OPEN" if self.current.doors_open else "CLOSED"
        door_color = self.GREEN if self.current.doors_open else self.YELLOW
        pygame.draw.circle(self.screen, door_color, (489, 273), 7)
        self._text(door_label, 507, 259, door_color, self.big_font)

        self._text("PENDING CALLS", 475, 322, self.MUTED, self.small)
        if self.current.calls:
            call_text = ", ".join(f"Floor {f}" for f in self.current.calls)
            self._text(call_text, 475, 355, self.RED, self.big_font)
            self._text(
                f"{len(self.current.calls)} pending call(s)",
                475, 392, self.MUTED, self.small
            )
        else:
            self._text("None", 475, 355, self.MUTED, self.big_font)

        self._text("ACTIONS IN THIS STATE", 475, 445, self.MUTED, self.small)
        action_text = ", ".join(self.current.actions) or "No movement / door action"
        # Keep long action lists within the panel.
        words = action_text.split(", ")
        line, y = "", 475
        for word in words:
            candidate = f"{line}, {word}" if line else word
            if self.small.size(candidate)[0] > 350:
                self._text(line, 475, y, self.TEXT, self.small)
                y += 22
                line = word
            else:
                line = candidate
        self._text(line, 475, y, self.TEXT, self.small)

    def _draw_timeline(self):
        count = len(self.snapshots)
        progress = f"State {self.index + 1} of {count}"
        self._center_text(progress, self.WIDTH // 2, 580, self.MUTED, self.small)

    def _draw_buttons(self):
        for rect, label, _action in self.buttons:
            enabled = True
            if _action == "first":
                enabled = self.index > 0
            elif _action == "previous":
                enabled = self.index > 0
            elif _action == "next":
                enabled = self.index < len(self.snapshots) - 1
            elif _action == "last":
                enabled = self.index < len(self.snapshots) - 1

            color = self.PANEL_LIGHT if enabled else (39, 45, 57)
            text_color = self.TEXT if enabled else (105, 115, 130)
            pygame.draw.rect(self.screen, color, rect, border_radius=9)
            pygame.draw.rect(self.screen, self.LINE, rect, 1, border_radius=9)
            self._center_text(label, rect.centerx, rect.y + 10, text_color,
                              self.big_font)

    def _activate(self, action):
        if action == "first":
            self.index = 0
        elif action == "previous":
            self.index = max(0, self.index - 1)
        elif action == "next":
            self.index = min(len(self.snapshots) - 1, self.index + 1)
        elif action == "last":
            self.index = len(self.snapshots) - 1

    def run(self):
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_HOME:
                        self._activate("first")
                    elif event.key == pygame.K_END:
                        self._activate("last")
                    elif event.key in (pygame.K_LEFT, pygame.K_PAGEUP):
                        self._activate("previous")
                    elif event.key in (pygame.K_RIGHT, pygame.K_PAGEDOWN):
                        self._activate("next")
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    for rect, _label, action in self.buttons:
                        if rect.collidepoint(event.pos):
                            self._activate(action)
                            break

            self.draw()
            self.clock.tick(self.FPS)

        pygame.quit()


def choose_input_file() -> Path | None:
    """Use a native file picker when possible."""
    try:
        import tkinter as tk
        from tkinter import filedialog

        root = tk.Tk()
        root.withdraw()
        root.attributes("-topmost", True)
        filename = filedialog.askopenfilename(
            title="Select elevator states text file",
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
        )
        root.destroy()
        return Path(filename) if filename else None
    except Exception:
        return None


def main():
    parser = argparse.ArgumentParser(description="Visualize an elevator state trace.")
    parser.add_argument("input_file", nargs="?", help="Path to the states text file")
    parser.add_argument(
        "-n", "--floors", type=int, default=5,
        help="Number of floors (default: 5; floors are numbered 0..N-1)"
    )
    args = parser.parse_args()

    if args.floors < 1:
        parser.error("--floors must be at least 1")

    source = Path(args.input_file) if args.input_file else choose_input_file()
    if source is None:
        source = Path("states.txt")

    if not source.exists():
        print(
            f"Input file not found: {source}\n"
            "Pass a file path, choose one in the file picker, or create states.txt.",
            file=sys.stderr,
        )
        return 1

    try:
        snapshots = parse_states(source, args.floors)
    except ValueError as exc:
        print(f"Input error: {exc}", file=sys.stderr)
        return 1

    if not snapshots:
        print("The input file contains no states.", file=sys.stderr)
        return 1

    try:
        ElevatorViewer(snapshots, args.floors, source).run()
    except pygame.error as exc:
        print(f"Could not start the Pygame window: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
