"""
init-mater-project

Copyright (C) 2025 [Lauranne Sarribouette] <lauranne.sarribouette@univ-grenoble-alpes.fr>

SPDX-License-Identifier: LGPL-3.0-or-later
"""

import sys
import streamlit as st
from pathlib import Path

from src.app import data, charts, components


def main():
    """Main MATER Streamlit app"""
    st.set_page_config(
        page_title="MATER Outputs Visualisation App",
        page_icon="📊",
        layout="wide",
        initial_sidebar_state="expanded",
    )

    # Parse output folder from command line
    output_folder = None

    for i, arg in enumerate(sys.argv):
        if arg == "--output-folder" and i + 1 < len(sys.argv):
            output_folder = Path(sys.argv[i + 1])
            break

    if not output_folder:
        output_folder = Path("outputs")

    # Detect output structure
    structure_mode, error_msg = data.detect_output_structure(output_folder)

    if structure_mode == data.OutputStructure.INVALID:
        st.error("⚠️ Invalid Output Folder Structure")
        st.markdown(error_msg)
        st.info(
            "💡 **Tip:** Run a simulation first:\n"
            "```bash\n"
            "uv run mater-cli simulation run --example\n"
            "```"
        )
        return

    simulations = None
    if structure_mode == data.OutputStructure.MULTIPLE_SIMULATIONS:
        simulations = data.get_available_simulations(output_folder)

        if not simulations:
            st.error(f"No simulations found in {output_folder}")
            st.info(
                "Run a simulation first: `uv run mater-cli simulation run --example`"
            )
            return

    # Render sidebar
    selected_simulation, selected_variable, dimension_filters = (
        components.render_sidebar(output_folder, structure_mode, simulations)
    )

    # Validate selections
    if not selected_variable:
        st.info("👈 Select a variable from the sidebar")
        return

    # Determine simulation path
    if structure_mode == data.OutputStructure.MULTIPLE_SIMULATIONS:
        if not selected_simulation:
            st.error("No simulation selected")
            return
        simulation_path = output_folder / selected_simulation
    else:
        simulation_path = output_folder

    # Load data (single variable)
    with st.spinner("Loading data..."):
        df = data.load_variable_data(simulation_path, selected_variable)

    if df.empty:
        st.error(
            f"⚠️ Cannot load data from {simulation_path}. "
            "Check that simulation outputs exist."
        )
        return

    # Validate dimension filters
    is_valid, error_msg = data.validate_dimension_filters(dimension_filters)
    if not is_valid:
        st.error(f"⚠️ {error_msg}")
        st.info("💡 Tip: Use checkbox to select all values")
        return

    # Create tabs
    time_series, area, snapshot, heatmap, raw_data, info = st.tabs(
        [
            "📊 Time Series",
            "📈 Area",
            "🎯 Snapshot",
            "🔥 Heatmap",
            "📋 Raw Data",
            "ℹ️ Info",
        ]
    )

    with time_series:
        charts.display_time_series_tab(df, dimension_filters)

    with area:
        charts.display_area_tab(df, dimension_filters)

    with snapshot:
        charts.display_snapshot_tab(df, dimension_filters)

    with heatmap:
        charts.display_heatmap_tab(df, dimension_filters)

    with raw_data:
        charts.display_raw_data_tab(df, dimension_filters, selected_simulation)

    with info:
        components.display_simulation_info(
            selected_simulation, selected_variable, df, structure_mode, simulation_path
        )


if __name__ == "__main__":
    main()
