import pandas as pd
import datetime
import os
from plotly_resampler import FigureResampler
import plotly.graph_objects as go
from eda_ts.constants import PLOTLY_PORT
import numpy as np
import pandas as pd
import streamlit as st

def format_value(v):
    if isinstance(v, bool):
        return "✅ Yes" if v else "❌ No"
    if pd.isna(v):
        return "N/A"
    if isinstance(v, (pd.Timestamp, datetime.datetime)):
        return v.strftime("%Y-%m-%d %H:%M:%S")
    return str(v)

def is_invalid_path(pkl_path) -> bool:
    return (
        pkl_path is None or
        not isinstance(pkl_path, str) or
        not os.path.exists(pkl_path)
    )

def dummy_data():
    """Generate dummy data for testing"""
    n_points = 20000
    time_index = pd.date_range(start=pd.Timestamp('2024-01-01'),  periods=n_points, freq='5min')
    x = np.arange(n_points)
    noise = np.random.normal(0, 0.1, n_points)
    df = pd.DataFrame({
        'Weekly Cycle': 4 * np.sin(2 * np.pi * x / 7) + 5 + noise,  # 7-day period,
        'Mixed Frequencies': 3 * np.sin(2 * np.pi * x / 7) + 5 + np.cos(2 * np.pi * x / (7/3)) + noise,  # Mixed 7-day and 2.33-day periods,
        'Monthly+Daily': 2 * np.sin(2 * np.pi * x / 30) + 3 * np.cos(2 * np.pi * x / 1) + 4 + noise  # 30-day and 1-day periods
    }, index=time_index)
    return df

        
def plotly_resample(
    df: pd.DataFrame,
    cols: list[str] | None = None,
    default_n_shown_samples: int = 2000,
    plot_height: int = 800,
    plot_margin: dict = dict(l=20, r=20, t=30, b=0),
    xaxis_title: str = "Datetime",
    yaxis_title: str = "Values",
) -> None:
    """
    Runs plotly resample in a subprocess to avoid blocking the main thread and enabling resample with zoom.
    Kills any previous process running on the same port to avoid conflicts.
    """
    cols = cols if cols is not None else df.columns
    fig = FigureResampler(go.Figure(), default_n_shown_samples=default_n_shown_samples)
    for col in cols:
        fig.add_trace(go.Scattergl(name=col, showlegend=True), hf_x=df.index, hf_y=df[col])
    fig.update_layout(
        xaxis_title=xaxis_title,
        yaxis_title=yaxis_title,
        margin=plot_margin,
        height=plot_height
    )
    fig.show_dash(mode="external", port=PLOTLY_PORT)
    st.components.v1.iframe(f"http://localhost:{PLOTLY_PORT}", height=800)