# app.py

import os
import json
import streamlit as st
from dotenv import load_dotenv
from openai import AzureOpenAI

# --------------------- ENV ---------------------
load_dotenv()

AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
AZURE_OPENAI_KEY = os.getenv("AZURE_OPENAI_KEY")
AZURE_OPENAI_DEPLOYMENT = os.getenv("AZURE_OPENAI_DEPLOYMENT")
AZURE_OPENAI_API_VERSION = os.getenv("AZURE_OPENAI_API_VERSION")

# --------------------- CLIENT ---------------------
openai_client = AzureOpenAI(
    azure_endpoint=AZURE_OPENAI_ENDPOINT,
    api_key=AZURE_OPENAI_KEY,
    api_version=AZURE_OPENAI_API_VERSION
)

# --------------------- FUNCTIONS ---------------------
def generate_summary(data):
    # Create analysis prompt
    system_prompt = """Analyze the JSON order activity log below and create a structured summary. Focus on:  
1. **Final Outcome**: Clearly state if the order was *Cancelled* or *Returned* or anything else (with reasons from the data and outcome and last recorded activity).  
2. **Order Timeline Overview** (creation timestamp, final status, key users/teams involved)  
3. **Critical Events**: Chronological breakdown of:  
   - Fraud checks (declines, locks, emails)  
   - Payment actions (authorization, voids)  
   - Cancellation/return triggers (e.g., "Order Cancelled" descriptions)  
   - Post-resolution access (e.g., coaching/reviews).  
4. **Key Notes** (patterns, automation flags, unusual access patterns, or notable reasons)    
5. **Key Evidence**: Specific JSON entries proving the outcome (e.g., "Cancelled due to DECLINED: Fraud").  

**Structure Requirements**:  
- Use markdown headers and bullet points.  
- Differentiate between system automation (e.g., "DOT COM") and human actions.  
- Group repeated events (e.g., multiple "Coaching" logs).  
- Highlight the *exact reason* for cancellation/return from the "text" or "description" fields.  

**Rules**:  
- If "Cancelled" appears in any "description" or "text" field, declare it as the outcome.  
- If "Returned" is not explicitly mentioned, assume cancellation.  
- Never guess – use only the provided JSON for conclusions."""

    try:
        response = openai_client.chat.completions.create(
            model=AZURE_OPENAI_DEPLOYMENT,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": json.dumps(data, indent=2)}
            ],
            temperature=0
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error generating summary: {str(e)}"

# --------------------- STREAMLIT UI ---------------------
st.set_page_config("Macy's Notes Analyzer", layout="wide")
st.title("📑 Macy's Notes Analysis — Direct LLM Processing")

uploaded_file = st.file_uploader("Upload Macy's JSON Notes", type="json")

if uploaded_file:
    try:
        data = json.load(uploaded_file)
        
        with st.spinner("🔍 Analyzing documents..."):
            summary = generate_summary(data)
            
        st.success("✅ Analysis Complete!")
        
        # Display formatted summary
        st.markdown("## 📝 Comprehensive Summary")
        st.markdown(summary)
                
    except json.JSONDecodeError:
        st.error("❌ Invalid JSON file format")
    except Exception as e:
        st.error(f"❌ Processing error: {str(e)}")

# Optional: Add original data preview
if uploaded_file and st.checkbox("Show raw data preview"):
    uploaded_file.seek(0)
    st.json(json.load(uploaded_file))

convert this code in python flask api with file strucutre like llm, routes,