import streamlit as st
import os


class StreamlitTOONViewer:
    def __init__(self) -> None:
        # Get the directory where this file is located
        _dir = os.path.dirname(os.path.abspath(__file__))

        with open(os.path.join(_dir, "frontend", "index.html"), "r") as f:
            self.html = f.read()
        with open(os.path.join(_dir, "frontend", "styles.css"), "r") as f:
            self.css = f.read()
        with open(os.path.join(_dir, "frontend", "index.js"), "r") as f:
            self.js = f.read()

        self.toon_viewer = st.components.v2.component(
            name="streamlit_toon",
            html=self.html,
            css=self.css,
            js=self.js,
        )

    def display_toon(self, data, height=400, key=None):
        """
        Display TOON data in a collapsible/expandable tree view.

        Parameters:
        -----------
        toon_data : str or dict
            TOON text as a string, or file path to a TOON file
        height : int, optional
            Height of the component in pixels (default: 400)
        key : str, optional
            Unique key for the component

        Returns:
        --------
        Component return value
        """
        # If toon_data is a file path, read it
        if isinstance(data, str) and os.path.isfile(data):
            with open(data, "r") as f:
                data = f.read()

        # V2 components require data as first positional argument (dict)
        return self.toon_viewer(
            data=data,
            key=key,
        )


toon_viewer = StreamlitTOONViewer()
toon_viewer.display_toon(
    data="""
context{task,location,season}: Our favorite hikes together,Boulder,spring_2025.
friends[3]: ana,luis,sam.
hikes[3]{id,name,distanceKm,elevationGain,companion,wasSunny}:
  1,Blue Lake Trail,7.5,320,ana,true.
  2,Ridge Overlook,9.2,540,luis,false.
  3,Wildflower Loop,5.1,180,sam,true."""
)
