import streamlit as st
import json
import os
from utils.report_loader import load_report
from components.risk_severity import render_risk_severity
from components.security_findings import render_security_findings
from components.strategy_table import render_strategy_table

def create_dashboard():
    st.set_page_config(
        page_title="AI Security Risk Dashboard", 
        page_icon=":shield:", 
        layout="wide"
    )
    
    st.title("🛡️ AI Security Risk Assessment")
    
    # Sidebar for file upload
    st.sidebar.header("Report Upload")
    uploaded_file = st.sidebar.file_uploader(
        "Choose a JSON report", 
        type=['json'], 
        help="Upload the JSON report generated by compliant-llm"
    )
    
    # Default report path
    report_dir = "reports"
    
    # If no file is uploaded, find the latest report
    if uploaded_file is None:
        if os.path.exists(report_dir):
            # Find all report files with timestamp format
            report_files = [f for f in os.listdir(report_dir) 
                          if f.startswith("report_") and 
                          f.endswith(".json") and
                          len(f) == len("report_YYYYMMDD_HHMMSS.json")]
            if report_files:
                # Sort by timestamp (which is in the filename)
                latest_file = sorted(report_files)[-1]
                default_report_path = os.path.join(report_dir, latest_file)
            else:
                default_report_path = None
        else:
            default_report_path = None
    
    # Determine which report to load
    if uploaded_file is not None:
        report_data = json.load(uploaded_file)
    else:
        try:
            report_data = load_report(default_report_path)
        except:
            st.warning("No default report found. Please upload a report.")
            return
    
    if not report_data:
        st.error("Unable to load report data")
        return
    
    # Sidebar for risk configuration
    st.sidebar.header("Risk Configuration")
    risk_tolerance = st.sidebar.slider("Risk Tolerance", 0, 100, 30)
    
    # Main dashboard sections
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("Total Security Tests", report_data['metadata']['test_count'], 
                  help="Number of security assessments performed")
    with col2:
        st.metric("Passed Tests", report_data['metadata']['success_count'], 
                  help="Tests that passed security checks")
    with col3:
        st.metric("Failed Tests", report_data['metadata']['failure_count'], 
                  help="Tests that failed security checks")
    
    # Render dashboard components
    render_strategy_table(report_data)
    render_security_findings(report_data)
    render_risk_severity(report_data)

def main():
    create_dashboard()

if __name__ == "__main__":
    main()