import streamlit as st
import openai
import os
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.utils import simpleSplit

# ===== Azure Text Bot Class =====
class AzureTextBot:
    def __init__(self, api_key, endpoint, deployment_id, api_version):
        self.client = openai.AzureOpenAI(
            api_key=api_key,
            api_version=api_version,
            azure_endpoint=endpoint,
        )
        self.deployment_id = deployment_id

    def read_txt_file(self, file_path):
        with open(file_path, "r", encoding="utf-8") as f:
            return f.read()

    def generate_summary(self, context, prompt_type):
        if prompt_type == "Earnings Summary":
            prompt = f"""
**Task:** Generate a concise, structured slide on earnings summaries for retail/consumer companies.  
**Input Context:**  
{context}  

**Slide Content Requirements:**  
1. **Title:** "Earnings Summary - [Week/Month] [Year]"  
2. **Summary of the Week** (1-2 sentences):  
   - Highlight key trends (e.g., "Strong retail sales offset tech misses").  
3. **Key Headers & Details** (use bullet points):  
   • **Trading Day of Print:**  
     - **Up:** List tickers with gains (>0.5%) and percentages (e.g., "GAP (+18%)").  
     - **Down:** List tickers with losses (<-0.5%) and percentages (e.g., "BBY (-13.3%)").  
   • **Trading Week Prior to Print:**  
     - Same format as above, but for the prior week.  
   • **Results vs. Consensus:**  
     - **Sales Beat/Miss:** Group tickers (e.g., "Beat: ANF, TGT; Miss: M, ROST").  
     - **Adj. EPS Beat/Miss:** Same as above.  
   • **Annual Guidance Updates:**  
     - **Sales Guidance:** "Provided by: [Tickers]; Not provided by: [Tickers]."  
     - **EPS Guidance:** Same as above.  

**Formatting Rules:**  
- Use `•` for main bullets, `-` for sub-bullets.  
- Bold headers (`**Trading Day of Print:**`).  
- Sort companies by magnitude of price changes (largest first).  
- Add a footnote if data is incomplete (e.g., "*PRDSY did not report EPS").  

**Example Output (for context):**  
Title: **Earnings Summary - Week of May 2024**  
Summary: Retail outperformed with Gap (+18%) leading gains, while tech dragged (BBY -13.3%).  
Allways make into the following format:
• **Trading Day of Print:**  
  - **Up:** GAP (+18%), BJ (+12.2%), BURL (+8.7%).  
  - **Down:** BBY (-13.3%), ANF (-9.2%), VSCO (-8.2%).  
• **Trading Week Prior to Print:**  
  - **Up:** BJ (+12.5%), GAP (+2.4%).  
  - **Down:** VSCO (-24.2%), ANF (-16.2%).  
• **Results vs. Consensus:**  
  - **Sales Beat:** ANF, TGT, GAP. **Miss:** M, ROST.  
  - **EPS Beat:** ANF, TGT. **Miss:** COST, AZO.  
• **Annual Guidance Updates:**  
  - **Sales Guidance:** Provided by ANF, TGT. Not provided by COST, KR.  
  - **EPS Guidance:** Provided by TGT. Not provided by GAP, VSCO.  
"""
        elif prompt_type == "Detailed Hot Topics (Positive / Neutral / Negative)":
            prompt = f"""
You are a financial analyst assistant. Based on the earnings and retail commentary text I provide, produce a **detailed and categorized Hot Topic Summary** using the exact structure below. Your responses must be **descriptive, professional, and well-organized** — **do not use one-liner summaries**. Include **all companies mentioned** in the text and apply the proper sentiment tags only where indicated. Follow this format exactly:

---

**Hot Topics**  
• Start with a paragraph summarizing the overall tone or sentiment across companies (e.g., cautious optimism, softening trends, improving momentum, etc.).

---

1. **Consumer Health Commentary**  
• Begin with a detailed summary paragraph on consumer behavior and demand trends across the companies.  
• Then group company commentary under the following **required sentiment labels**:  
   - **Positive**  
   - **Neutral**  
   - **Negative**  
• Within each sentiment group, use bullet points. Each bullet must begin with the company name in bold, followed by a detailed description of their consumer-related commentary.  

---

2. **QTD Performance**  
• Start with a paragraph summarizing quarter-to-date trends.  
• Then categorize company-specific comments under these headings (required):  
   - **Positive**  
   - **Neutral**  
   - **Negative**  
• Use bullet points under each heading. Each bullet must begin with the company name in bold and describe their QTD trends in detail.  

---

3. **Fiscal Year Expectations**  
• Provide a detailed summary of fiscal year guidance and outlooks (e.g., FY24, FY25).  
• Use bullet points starting with company names in bold, followed by their guidance commentary.

---

4. **Tariff Commentary**  
• Provide a paragraph summarizing how tariffs or trade policies are impacting performance.  
• Then use bullet points beginning with company names in bold, followed by tariff-related commentary.

---

5. **Weather Commentary**  
• Summarize how weather trends are affecting companies.  
• Then list each relevant company in bold with their respective weather-related commentary.

---

6. **Stock Initiations and Re-Ratings**  
• Provide a detailed summary of analyst rating changes or new stock coverage.  
• Use bullet points starting with company names in bold, followed by details of the rating/initiation.

---

7. **Largest Stock Movements**  
• Summarize notable stock price changes across companies, with reasoning if mentioned.  
• Use bullet points starting with company names in bold, followed by details of the movement and drivers.

---

⚠️ Important Notes:  
• Use **Positive / Neutral / Negative** tags **only in the Consumer Health Commentary and QTD Performance sections**.  
• Every section should be **detailed and professional** — **do not summarize in a single sentence**.  
• Use proper bullet formatting and structure.  

---

Here is the text to analyze:  
{context}
"""
        else:
            prompt = f"Summarize this document clearly for investor insight:\n\n{context}"

        messages = [
            {"role": "system", "content": "You are a helpful financial analyst assistant."},
            {"role": "user", "content": prompt}
        ]

        response = self.client.chat.completions.create(
            model=self.deployment_id,
            messages=messages,
            temperature=0.3
        )
        return response.choices[0].message.content.strip()



def create_pdf(content_dict):
    file_path = os.path.join("temp", f"summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf")
    os.makedirs("temp", exist_ok=True)

    c = canvas.Canvas(file_path, pagesize=letter)
    width, height = letter
    margin = 50
    y = height - margin
    line_height = 14
    max_width = width - 2 * margin

    for title, content in content_dict.items():
        if y < margin + 100:
            c.showPage()
            y = height - margin

        # Draw Main Title (e.g., "Consumer Health Commentary")
        c.setFont("Helvetica-Bold", 16)
        c.drawString(margin, y, title)
        y -= line_height * 1.5

        # Prepare content
        lines = content.split("\n")

        for line in lines:
            stripped_line = line.strip()

            if not stripped_line:
                y -= line_height * 0.5
                continue

            # Section Subheadings (e.g., Positive, Negative, Neutral)
            if stripped_line in ["Positive", "Neutral", "Negative"]:
                if y < margin + line_height:
                    c.showPage()
                    y = height - margin
                c.setFont("Helvetica-Bold", 13)
                c.drawString(margin + 10, y, stripped_line)
                y -= line_height * 1.2
                continue

            # Bullet points or regular paragraph
            bullet_indent = 20
            if stripped_line.startswith("•") or stripped_line.startswith("-"):
                text = stripped_line
                c.setFont("Helvetica", 11)
            else:
                text = stripped_line
                c.setFont("Helvetica", 12)

            # Wrap long lines
            wrapped = simpleSplit(text, c._fontname, c._fontsize, max_width)
            for wrap_line in wrapped:
                if y < margin + line_height:
                    c.showPage()
                    y = height - margin
                c.drawString(margin + bullet_indent, y, wrap_line)
                y -= line_height

        # Add spacing after each major section
        y -= line_height * 2

    c.save()
    return file_path



# ===== Streamlit UI =====
st.set_page_config(page_title="📈 Macy's Earnings Summary", layout="wide")
st.title("📈 Summarize Macy’s Earnings from a Transcript File")

# Load Azure API credentials
api_key = st.secrets["AZURE_API_KEY"]
endpoint = st.secrets["AZURE_ENDPOINT"]
deployment_id = st.secrets["AZURE_DEPLOYMENT"]
api_version = st.secrets["AZURE_API_VERSION"]

bot = AzureTextBot(api_key, endpoint, deployment_id, api_version)

# Session state
if "summaries" not in st.session_state:
    st.session_state.summaries = {}

uploaded_file = st.file_uploader("Upload a `.txt` file with Macy's earnings info", type=["txt"])

if uploaded_file:
    st.markdown("### Select summary types and click Submit:")
    prompt_types = st.multiselect(
        "Select the types of summaries you want to generate",
        ["Earnings Summary", "Detailed Hot Topics (Positive / Neutral / Negative)", "Basic Summary"]
    )

    if st.button("🚀 Submit"):
        if prompt_types:
            with st.spinner("Reading file and summarizing..."):
                file_path = os.path.join("temp", f"temp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt")
                os.makedirs("temp", exist_ok=True)
                with open(file_path, "wb") as f:
                    f.write(uploaded_file.read())

                context = bot.read_txt_file(file_path)
                summaries = {}

                for ptype in prompt_types:
                    summaries[ptype] = bot.generate_summary(context, ptype)

                st.session_state.summaries = summaries
                os.remove(file_path)
                st.success("✅ All summaries generated!")
        else:
            st.warning("⚠️ Please select at least one summary type.")

# Display summaries and download PDF
if st.session_state.summaries:
    for key, value in st.session_state.summaries.items():
        st.subheader(f"📄 {key}")
        st.markdown(value)

    pdf_path = create_pdf(st.session_state.summaries)
    with open(pdf_path, "rb") as f:
        st.download_button("📥 Download All Summaries as PDF", f, file_name="earnings_summary.pdf", mime="application/pdf")


with this code we are not able to get exact values and company in Earning summary as well as in Hot topics so can we read the file preapre the embeddings with the parargraphs of 200 words and overlpaing 50 words and can get the summary with the embeddings and make that summary with that