"""台灣登山路線規劃輔助系統 - Streamlit Web Application"""

import streamlit as st
from elevation_profile import ElevationProfileRenderer
from gpx import GPXProcessor
from map_render import MapRenderer
from streamlit_folium import st_folium
from weather import WeatherFetcher


def main():
    """Main Streamlit application."""
    # Page configuration
    st.set_page_config(
        page_title='臺灣登山路線分析小幫手',
        page_icon='assets/favicon_compressed.jpg',
        layout='wide',
        initial_sidebar_state='collapsed',
    )

    # Title and description
    st.title('⛰️ 臺灣登山路線分析小幫手')
    st.markdown('上傳您的 GPX 檔案開始分析路線！')

    # File uploader
    uploaded_file = st.file_uploader(
        '上傳檔案',
        type=['gpx'],
        help='請上傳包含登山路線的 GPX 檔案',
    )

    if uploaded_file is not None:
        try:
            # Process GPX file
            with st.spinner('正在解析 GPX 檔案...'):
                gpx_processor = GPXProcessor(uploaded_file)

                if not gpx_processor.validate_and_parse():
                    st.error('❌ GPX 檔案格式錯誤或不包含有效的軌跡點')
                    return

                # Calculate statistics
                total_distance = gpx_processor.calculate_distance()
                elevation_gain, elevation_loss = gpx_processor.calculate_elevation_gain_loss()
                min_elevation, max_elevation = gpx_processor.get_min_max_elevation()
                start_point, end_point = gpx_processor.get_start_end_points()
                all_points = gpx_processor.get_all_points()
                distances, elevations = gpx_processor.get_elevation_profile_data()
                gradients = gpx_processor.get_gradients()

            # Display statistics section
            st.header('📊 路線統計資訊')
            col1, col2, col3, col4, col5 = st.columns(5)

            with col1:
                st.metric(label='總距離', value=f'{total_distance:.2f}', delta='公里')

            with col2:
                st.metric(label='總爬升', value=f'{elevation_gain:.0f}', delta='公尺')

            with col3:
                st.metric(label='總下降', value=f'{elevation_loss:.0f}', delta='公尺')

            with col4:
                st.metric(label='最高海拔', value=f'{max_elevation:.0f}', delta='公尺')

            with col5:
                st.metric(label='最低海拔', value=f'{min_elevation:.0f}', delta='公尺')

            st.divider()

            # Map and Elevation profile section (no divider between them)
            st.header('🗺️ 路線地圖')

            # Map section
            with st.spinner('正在渲染地圖...'):
                map_renderer = MapRenderer()
                route_map = map_renderer.create_route_map(all_points, start_point, end_point)

                if route_map:
                    st_folium(route_map, width=None, height=500)
                else:
                    st.error('無法渲染地圖')

            # Elevation profile section (directly below map, no divider)
            # st.markdown('🔴 **紅色**表示上升路段（顏色越深坡度越陡） | 🟢 **綠色**表示下降路段（顏色越深坡度越陡）')

            # Create two columns: elevation profile on left, pie chart on right
            profile_col, pie_col = st.columns([2, 1])

            with profile_col:
                with st.spinner('正在繪製海拔剖面圖...'):
                    profile_renderer = ElevationProfileRenderer()
                    elevation_fig = profile_renderer.create_elevation_profile(distances, elevations, gradients)

                    if elevation_fig:
                        # Add legend
                        elevation_fig = profile_renderer.add_gradient_legend(elevation_fig)
                        st.plotly_chart(elevation_fig, width='stretch')
                    else:
                        st.error('無法繪製海拔剖面圖')

            with pie_col:
                with st.spinner('正在分析坡度分布...'):
                    pie_fig = profile_renderer.create_gradient_pie_chart(distances, gradients)

                    if pie_fig:
                        st.plotly_chart(pie_fig, width='stretch')
                    else:
                        st.error('無法繪製坡度分布圖')

            st.divider()

            # Weather section
            st.header('☀️ 起點天氣預報')

            if start_point:
                with st.spinner('正在獲取天氣資訊...'):
                    weather_fetcher = WeatherFetcher()
                    weather_data = weather_fetcher.get_weather(start_point[0], start_point[1])

                    if weather_data:
                        weather_info = weather_fetcher.format_weather_display(weather_data)

                        if weather_info:
                            # Current weather
                            st.subheader('當前天氣')
                            col1, col2, col3, col4 = st.columns(4)

                            with col1:
                                st.metric(label='🌡️ 溫度', value=weather_info['temperature'])

                            with col2:
                                st.metric(label='💧 濕度', value=weather_info['humidity'])

                            with col3:
                                st.metric(label='🌧️ 降雨量', value=weather_info['precipitation'])

                            with col4:
                                st.metric(label='💨 風速', value=weather_info['wind_speed'])

                            # Forecast
                            if weather_info['forecast']:
                                st.subheader('未來三天預報')
                                forecast_cols = st.columns(3)

                                for idx, forecast in enumerate(weather_info['forecast']):
                                    with forecast_cols[idx]:
                                        st.markdown(f'**{forecast["date"]}**')
                                        st.write(f'🌡️ 高溫: {forecast["temp_max"]}°C')
                                        st.write(f'🌡️ 低溫: {forecast["temp_min"]}°C')
                                        st.write(f'🌧️ 降雨機率: {forecast["precip_prob"]}%')
                        else:
                            st.warning('⚠️ 無法格式化天氣資料')
                    else:
                        st.warning('⚠️ 無法獲取天氣資訊，請稍後再試')
            else:
                st.warning('⚠️ 無法確定起點位置')

        except Exception as e:
            st.error(f'❌ 處理檔案時發生錯誤: {str(e)}')

    else:
        # # Show instructions when no file is uploaded
        # st.info('👆 請上傳 GPX 檔案開始分析')
        # st.markdown(
        #     """
        # ### 使用說明
        # 1. 點擊上方的「選擇 GPX 檔案」按鈕
        # 2. 選擇您的登山路線 GPX 檔案
        # 3. 系統將自動分析並顯示：
        #    - 📊 路線統計資訊（距離、爬升、海拔等）
        #    - 🗺️ 互動式路線地圖
        #    - 📈 海拔剖面圖（顏色顯示坡度變化）
        #    - ☀️ 起點天氣預報
        # """
        # )
        pass


if __name__ == '__main__':
    main()
