# src/pipeline/gui_plotly_static.py

import plotly.graph_objs as go
import plotly.offline as pyo
import webbrowser
import tempfile
import threading
from pipeline.environment import is_termux
import http.server
import time
from pathlib import Path
import os

buffer_lock = threading.Lock()  # Optional, if you want thread safety

# A simple HTTP server that serves files from the current directory.
# We suppress logging to keep the Termux console clean.
class PlotServer(http.server.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        return
    
def show_static(plot_buffer):
    """
    Renders the current contents of plot_buffer as a static HTML plot.
    Does not listen for updates.
    """
    if plot_buffer is None:
        print("plot_buffer is None")
        return

    with buffer_lock:
        data = plot_buffer.get_all()

    traces = []
    for label, series in data.items():
        traces.append(go.Scatter(
            x=series["x"],
            y=series["y"],
            mode="lines+markers",
            name=label
        ))

    layout = go.Layout(
        title="EDS Data Plot (Static)",
        margin=dict(t=40)
    )

    fig = go.Figure(data=traces, layout=layout)

    # Write to a temporary HTML file
    # Use Path to handle the temporary file path
    tmp_path = Path(tempfile.gettempdir()) / f"plotly_plot_{time.time_ns()}.html"
    
    # Write the plot to the file
    pyo.plot(fig, filename=str(tmp_path), auto_open=False)

    # Get the directory and filename using pathlib attributes
    tmp_dir = tmp_path.parent
    tmp_filename = tmp_path.name

    # Change the current working directory to the temporary directory.
    # This is necessary for the SimpleHTTPRequestHandler to find the file.
    # pathlib has no direct chdir equivalent, so we still use os.
    os.chdir(str(tmp_dir))

    # Start a temporary local server in a separate, non-blocking thread
    PORT = 8000
    server_address = ('', PORT)
    try:
        httpd = http.server.HTTPServer(server_address, PlotServer)
        # Setting daemon=True ensures the server thread will exit when the main program does
        server_thread = threading.Thread(target=httpd.serve_forever, daemon=True)
        server_thread.start()
    except OSError as e:
        print(f"Error starting server on port {PORT}: {e}")
        print("This is likely because another process is using the port.")
        print("Please try again later or manually navigate to the file.")
        print(f"File path: {tmp_path}")
        return

    # Construct the local server URL
    tmp_url = f'http://localhost:{PORT}/{tmp_filename}'
    print(f"Plot server started. Opening plot at:\n{tmp_url}")
    
    # Open the local URL in the browser
    webbrowser.open(tmp_url)
    
    # Keep the main thread alive for a moment to allow the browser to open.
    # The server will run in the background until the script is manually terminated.
    print("\nPlot displayed. Press Ctrl+C to exit this script and stop the server.")
    try:
        while server_thread.is_alive():
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nExiting.")
        httpd.shutdown()

# Example usage with a dummy plot_buffer and is_termux function
if __name__ == "__main__":
    class DummyPlotBuffer:
        def get_all(self):
            return {
                "Series A": {"x": [1, 2, 3], "y": [4, 1, 2]},
                "Series B": {"x": [1, 2, 3], "y": [2, 4, 5]}
            }

    # is_termux is not a standard Python function, so we mock it for this example
    def is_termux():
        return "termux" in os.environ.get("PATH", "").lower()

    show_static(DummyPlotBuffer())