from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
    QFrame, QPushButton, QScrollArea, QWidget,
    QTabWidget, QTextEdit
)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

class ManualDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("MASPY GUI - User Manual")
        self.setMinimumSize(900, 650)
        
        self.setWindowFlags(
            Qt.Window |
            Qt.WindowMinimizeButtonHint |
            Qt.WindowMaximizeButtonHint |
            Qt.WindowCloseButtonHint
        )
        
        self._setup_ui()

    def _setup_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)

        title = QLabel("MASPY GUI - User Manual")
        title.setProperty("class", "h1")
        title.setFont(QFont("Arial", 18, QFont.Bold))
        main_layout.addWidget(title)

        self.tabs = QTabWidget()
        self.tabs.addTab(self._create_overview_tab(), "Overview")
        self.tabs.addTab(self._create_interface_tab(), "Interface Guide")
        self.tabs.addTab(self._create_maspy_tab(), "MASPY Reference")
        
        self.tabs.setStyleSheet("""
            QTabBar::tab {
                min-width: 180px;
                min-height: 30px;
                padding: 8px 16px;
                font-size: 20px;
            }
        """)
        
        main_layout.addWidget(self.tabs, stretch=1)

        close_btn = QPushButton("Close")
        close_btn.setFixedWidth(120)
        close_btn.clicked.connect(self.accept)
        
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        btn_layout.addWidget(close_btn)
        main_layout.addLayout(btn_layout)

    def _create_scrollable_content(self, html_content):
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.NoFrame)
        
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)
        content_layout.setContentsMargins(10, 10, 10, 10)
        
        text_edit = QTextEdit()
        text_edit.setReadOnly(True)
        text_edit.setFrameShape(QFrame.NoFrame)

        styled_html = f"<div style='font-size: 20px;'>{html_content}</div>"
        text_edit.setHtml(styled_html)
        
        
        content_layout.addWidget(text_edit)
        scroll.setWidget(content_widget)
        
        return scroll

    def _create_overview_tab(self):
        html = """
        <h2>MASPY GUI</h2>
        <p>This interface is used for monitoring and debugging the execution of MASPY</p>
        
        <p><b>Main Features:</b></p>
        <ul>
            <li><b>Timeline Navigation:</b> Pause and navigate through the simulation history</li>
            <li><b>Agent Inspection:</b> View detailed information about each agent, monitoring agent behaviours, goals and percepts history</li>
            <li><b>Environment Tracking:</b> Monitor environment changes and percepts history</li>
            <li><b>Message Logging:</b> Analyze communication between agents</li>
            <li><b>Learning Visualization:</b> Observe Q-Learning models</li>
        </ul>
        
        <p><b>Tutorial guide:</b></p>
        <p>Use the <b>sidebar</b> on the left to navigate between different pages
        <p>The <b>timeline slider</b> at the top allows you to rewind and review past simulation states at a specific point in time
        """
        return self._create_scrollable_content(html)

    def _create_interface_tab(self):
        html = """
        <h2>Menu</h2>
        <p>The main page showing an overview of the simulation</p>
        <ul>
            <li><b>Intentions Report:</b> A chronological log of all intentions in the system
            Shows which agent created the intention, what the trigger was, and the intention details.</li>
            <li><b>Pause/Play:</b> When pressed will pause the simulation, press again to continue the execution. Note that if the simulation has ended this button will have no effect</li>
        </ul>
        
        <h2>Agents</h2>
        <p>View all agents in the system displayed as cards</p>
        <ul>
            <li><b>Agent Card:</b> Show agent name, cycle count, beliefs/goals count, and current action</li>
            <li><b>Search:</b> Filter agents by name</li>
            <li><b>View Details:</b> Click to open a detailed window with internal agent information</li>
            <ul>
                <li><b>Overview</b></li>
                <ul>
                    <li><b>Real Time Status:</b> Shows the current cycle, current action, processing event and number of intentions</li>
                    <li><b>Beliefs:</b> Shows the agent's beliefs</li>
                    <li><b>Running Intentions:</b> Shows the agent's intentions</li>
                    <li><b>Goals:</b> Shows the agent's goals</li>
                </ul>
                <li><b>Agent's mind</b></li>
                <ul>
                    <li><b>Beliefs History:</b> Shows all beliefs of the agent during system execution</li>
                    <li><b>Goals History:</b> Shows all goals of the agent during system execution</li>
                    <li><b>Intentions History:</b> Shows all intentions of the agent during system execution</li>
                </ul>
                <li><b>Environment and Channels</b></li>
                <ul>
                    <li><b>Perceptions:</b> Shows the environment perception state that the agent is connected to</li>
                    <li><b>Environments:</b> Shows the list of environments the agent is connected to</li>
                    <li><b>Channels:</b> Shows the list of channels the agent is connected to</li>
                </ul>
                <li><b>Learning</b></li>
                <ul>
                    <li><b>Q-Table:</b> Displays the agent's Q-Learning table with state-action values</li>
                    <li><b>Training Status:</b> Shows whether the learning model is still training or has completed</li>
                </ul>
            </ul>
        </ul>
        
        <h2>Environment</h2>
        <p>Monitor the environments in your multiagent system</p>
        <ul>
            <li><b>Connected Agents:</b> Shows which agents are connected to the environment</li>
            <li><b>Percepts:</b> Current state of the environment's percepts</li>
            <li><b>Changes History:</b> Log of all modifications in the percpetion system, showing the action type (CREATE, DELETE, CHANGE), the content of the change, and the action that triggered it</li>
        </ul>
        
        <h2>Messages</h2>
        <p>View all inter-agent communication</p>
        <ul>
            <li><b>Message Log:</b> All messages exchanged between agents</li>
            <li><b>Filters:</b> Filter by sender, receiver, or performative type</li>
        </ul>
        
        <h2>Learning</h2>
        <p>Visualize reinforcement learning models</p>
        <ul>
            <li><b>Models List:</b> All learning models in the system</li>
            <li><b>Q-Table:</b> The policy table showing state-action values</li>
            <li><b>Training Status:</b> Whether training is complete or in progress</li>
        </ul>
        """
        return self._create_scrollable_content(html)

    def _create_maspy_tab(self):
        html = """
        <h2>Multi-Agent Systems</h2>
        <p>A Multi-Agent System is a computational system composed of multiple autonomous agents that interact with each other and are situated in an environment</p>
        
        <p><b>Key characteristics of MAS:</b></p>
        <ul>
            <li><b>Autonomy:</b> Agents operate independently without direct external control</li>
            <li><b>Social Ability:</b> Agents communicate with each other</li>
            <li><b>Reactivity:</b> Agents perceive and respond to changes in the environmen</li>
        </ul>
        
        <h2>BDI Architecture</h2>
        <p>MASPY implements the BDI (Belief-Desire-Intention) architecture, a philosophical and computational model for rational agents. 
        This architecture models the practical reasoning process of agents based on three key components:</p>
        
        <p><b>Beliefs</b></p>
        <p>Beliefs represent the agent's knowledge about itself, other agents, and the environment. 
        They are the informational component of the agent's state and can be updated through perception or inference.</p>
        <ul>
            <li>Beliefs can be added, removed or modified during execution</li>
            <li>Changes in beliefs can trigger plans and generate new intentions</li>
        </ul>
        
        <p><b>Desires (Goals)</b></p>
        <p>Desires represent the motivational state of the agent, the objectives it wants to achieve.
        In MASPY, desires are implemented as Goals that the agent actively pursues.</p>
        <ul>
            <li>Goals define what the agent wants to accomplish</li>
            <li>Goals trigger the selection of appropriate plans</li>
        </ul>
        
        <p><b>Intentions</b></p>
        <p>Intentions represent the deliberative component, the plans the agent has committed to execute.</p>
        <ul>
            <li>Intentions are instantiated plans being executed</li>
            <li>Multiple intentions can run concurrently</li>
        </ul>
        
        <h2>MASPY Framework</h2>
        <p>MASPY is a Python framework for developing Multi-Agent Systems based on the BDI architecture. 
        It provides a structured way to define agents, environments, and communication channels.</p>
        
        <h3>Agents</h3>
        <p>In MASPY, agents are autonomous entities that follow the BDI reasoning cycle:</p>
        <ul>
            <li><b>Perception:</b> The agent perceives the environment through percepts</li>
            <li><b>Belief Update:</b> Percepts are processed and beliefs are updated accordingly</li>
            <li><b>Deliberation:</b> The agent selects which goals to pursue based on current beliefs</li>
            <li><b>Plan Selection:</b> Appropriate plans are selected to achieve the chosen goals</li>
            <li><b>Execution:</b> The agent executes actions from the selected plans</li>
        </ul>
        
        <p><b>Plans</b></p>
        <p>Plans define how agents achieve their goals. Each plan consists of:</p>
        <ul>
            <li><b>Trigger:</b> The event that activates the plan </li>
            <li><b>Context:</b> Conditions that need to exist for the plan to be applicable</li>
            <li><b>Body:</b> The sequence of actions and the plan itself</li>
        </ul>
        
        <h3>Environment</h3>
        <p>The Environment in MASPY is the shared space where agents perceive and act. 
        It manages percepts that agents can sense and actions that modify the world state.
        It is possible to create multiple environments with multiple agents</p>
        <ul>
            <li><b>Percepts:</b> Information available in the environment that agents can perceive</li>
            <li><b>Actions:</b> Operations that agents can perform to modify the environment</li>
            <li><b>Multiple agents</b> can be connected to the same environment</li>
        </ul>
        
        <h3>Communication</h3>
        <p>MASPY provides inter-agent communication through message passing using messages:</p>
        
        <p><b>Messages</b></p>
        <p>Messages are structured communications between agents containing:</p>
        <ul>
            <li><b>Sender:</b> The agent sending the message</li>
            <li><b>Receiver:</b> The target agent(s) for the message</li>
            <li><b>Performative:</b> The type of communicative: tell (Belief), achieve (Goal), ask</li>
            <li><b>Content:</b> The actual information being communicated</li>
        </ul>
        
        <p><b>Channels</b></p>
        <p>Channels are communication pathways that connect agents:</p>
        <ul>
            <li>Agents must be connected to a channel to send/receive messages</li>
            <li>Channels can be used for group communication</li>
            <li>Different channels can serve different communication purposes</li>
        </ul>
        
        <p><b>Performatives</b></p>
        <p>Performatives define the intent of a message:</p>
        <ul>
            <li><b>achieve:</b> Request that a goal be achieved</li>
            <li><b>tell:</b> Send a belief to another agent</li>
            <li><b>askOne/askAll:</b> Ask for information</li>
        </ul>
        
        <h3>Admin (ADM)</h3>
        <p>The Admin component manages the overall execution of the multi-agent system:</p>
        <ul>
            <li><b>Configuration:</b> System settings and initialization parameters</li>
        </ul>
        
        """
        return self._create_scrollable_content(html)