import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
from io import BytesIO

# Define fixed template paths
NOMINEE_TEMPLATE_PATH = r"C:\Users\Administrator\Desktop\AsiaLaw\Asia Law.docx"  # Fixed path for nominee template
SIMPLE_TEMPLATE_PATH = r"C:\Users\Administrator\Desktop\AsiaLaw\Asia Lawnormal.docx"  # Fixed path for simple template
BEFORE_DOCX_PATH = r"C:\Users\Administrator\Desktop\AsiaLaw\Before.docx"  # New path for before pages
BETWEEN_DOCX_PATH = r"C:\Users\Administrator\Desktop\AsiaLaw\Between.docx"  # New path for between pages
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\AsiaLaw\Asia Law...docx"  # New path for after pages

def create_individual_document(template_path, data, matter_count, output_path, form_type):
    """Create an individual document for a row of data based on the template."""
    doc = Document(template_path)
    
    # Find the table in the document
    if len(doc.tables) < 1:
        st.error("Template document does not contain the expected table.")
        return None
    
    table = doc.tables[0]

    # Map Excel fields to table cells based on the form structure
    # Different mapping depending on form type
    field_mapping = {
        "Case overview": data.get("Matter/Case Overview", ""),
        "Confidential/Partially confidential (Yes or no)": data.get("Confidential / Publishable ", ""),
        "Dispute resolution practice area(s)": data.get("Practice Area", "") if "Practice Area" in data else "",
        "Industry sector(s)": data.get("Industry Sector", "") if "Industry Sector" in data else "",
        "Date completed (MM/YY) / Ongoing": data.get("Current Status (ongoing / completed )", ""),
        "Value (currency)	": data.get("Value ", ""),
        "Client (s) advised": data.get("Client Name ", ""),
        "Lead partner involved": data.get("Lead partners", ""),
        "Other lawyers involved": data.get("Team Members", ""),
        "Your firm’s role": data.get("Role of S&A", ""),
        "Other law firms and their roles": data.get("Other Firms/counsels Involved", ""),
        "Governing law": "Indian Law",  # Default value
        "Description": data.get("Description  (in 500 words)", ""),
        "Please state the significance, impact and outcome of the deal/case": data.get("The significance, impact and outcome of the case", "")
    }
    
    # Update the title based on form type
    for paragraph in doc.paragraphs:
        if "WORK HIGHLIGHT" in paragraph.text:
            paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
            for run in paragraph.runs:
                run.font.bold = True
    
    # Populate the table with data
    for row in table.rows:
        if len(row.cells) >= 2:  # Ensure the row has at least two cells
            cell_text = row.cells[0].text.strip()
            if cell_text in field_mapping:
                row.cells[1].text = str(field_mapping[cell_text])
    
    # Save the individual document
    doc.save(output_path)
    return output_path

def append_docs(doc_list, output_doc):
    """Combine multiple Word documents into one, preserving watermarks."""
    combined_doc = Document()
    
    for doc_path in doc_list:
        # Skip if file doesn't exist
        if not os.path.exists(doc_path):
            continue
            
        sub_doc = Document(doc_path)
        
        # Copy content from sub_doc to combined_doc
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)
    
    combined_doc.save(output_doc)
    return output_doc

def process_benchmark_forms(excel_file, selected_nominee_indices, selected_simple_indices, use_before=True, use_between=True, use_after=True):
    """Generate the Asia Awards forms based on the selected Excel rows with additional pages."""
    try:
        # Read Excel file
        df = pd.read_excel(excel_file)
        nominee_docs = []
        simple_docs = []
        
        # Process nominee selections first
        nominee_count = 1
        for index in selected_nominee_indices:
            row = df.iloc[index]
            temp_output_path = f"temp_nominee_{nominee_count}.docx"
            
            individual_doc_path = create_individual_document(
                NOMINEE_TEMPLATE_PATH,  # Use fixed nominee template
                row, 
                nominee_count, 
                temp_output_path,
                "nominee"
            )
            
            if individual_doc_path:
                nominee_docs.append(individual_doc_path)
                nominee_count += 1
        
        # Then process simple work highlights
        simple_count = 1
        for index in selected_simple_indices:
            row = df.iloc[index]
            temp_output_path = f"temp_simple_{simple_count}.docx"
            
            individual_doc_path = create_individual_document(
                SIMPLE_TEMPLATE_PATH,  # Use fixed simple work highlight template
                row, 
                simple_count, 
                temp_output_path,
                "simple"
            )
            
            if individual_doc_path:
                simple_docs.append(individual_doc_path)
                simple_count += 1
        
        # Combine all documents with before, between, and after pages
        if nominee_docs or simple_docs:
            combined_doc_list = []
            
            # Add before pages if requested and file exists
            if use_before and os.path.exists(BEFORE_DOCX_PATH):
                combined_doc_list.append(BEFORE_DOCX_PATH)
            
            # Add nominee documents
            combined_doc_list.extend(nominee_docs)
            
            # Add between pages if requested and file exists
            if use_between and os.path.exists(BETWEEN_DOCX_PATH) and simple_docs:
                combined_doc_list.append(BETWEEN_DOCX_PATH)
            
            # Add simple documents
            combined_doc_list.extend(simple_docs)
            
            # Add after pages if requested and file exists
            if use_after and os.path.exists(AFTER_DOCX_PATH):
                combined_doc_list.append(AFTER_DOCX_PATH)
            
            # Combine all documents (preserving watermarks)
            combined_output_path = "combined_asia_forms.docx"
            append_docs(combined_doc_list, combined_output_path)
            
            # Clean up temporary files
            for doc_path in nominee_docs + simple_docs:
                if os.path.exists(doc_path):
                    try:
                        os.remove(doc_path)
                    except:
                        pass
                
            return combined_output_path
        
    except Exception as e:
        st.error(f"Error processing documents: {str(e)}")
        return None

# Streamlit application
def app():
    st.title("Asia Law Awards 2025 Form")
    
    # Upload files
    st.subheader("Upload Excel Data")
    excel_file = st.file_uploader("Upload Excel Data File", type=["xlsx", "xls"])
    
    # Client selection section
    if excel_file is not None:
        # Read the Excel file
        df = pd.read_excel(excel_file)
        
        # Check if the required column exists
        if "Client Name " in df.columns:
            # Create tabs for the two different form types
            tab1, tab2, tab3 = st.tabs(["Nominee Work Highlights", "Simple Work Highlights", "Document Options"])
            
            with tab1:
                st.subheader("Select Nominee Work Highlights (Maximum 3)")
                st.write("Select up to 3 matters for nominee work highlights:")
                
                # Create container for nominee selection
                nominee_container = st.container()
                
                # Track selected nominee indices
                selected_nominee_indices = []
                
                with nominee_container:
                    for i, client in enumerate(df["Client Name "]):
                        # Display additional information to help identify each client
                        matter_info = f"{client}"
                        if "Matter/Case Overview" in df.columns:
                            matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
                        
                        # Create checkbox for each client
                        # Disable checkbox once 3 are selected
                        disabled = len(selected_nominee_indices) >= 3 and i not in selected_nominee_indices
                        
                        if st.checkbox(matter_info, key=f"nominee_{i}", disabled=disabled):
                            if i not in selected_nominee_indices:
                                selected_nominee_indices.append(i)
                        elif i in selected_nominee_indices:
                            selected_nominee_indices.remove(i)
                
                st.write(f"Selected nominee matters: {len(selected_nominee_indices)} out of 3 maximum")
                
                # Warning if more than 3 selected
                if len(selected_nominee_indices) > 3:
                    st.warning("You have selected more than 3 nominee matters. Only the first 3 will be processed.")
                    selected_nominee_indices = selected_nominee_indices[:3]
            
            with tab2:
                st.subheader("Select Simple Work Highlights")
                st.write("Select any number of matters for simple work highlights:")
                
                # Create container for simple selection
                simple_container = st.container()
                
                # Track selected simple indices
                selected_simple_indices = []
                
                with simple_container:
                    for i, client in enumerate(df["Client Name "]):
                        # Skip if already selected as nominee
                        if i in selected_nominee_indices:
                            continue
                            
                        # Display additional information to help identify each client
                        matter_info = f"{client}"
                        if "Matter/Case Overview" in df.columns:
                            matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
                        
                        # Create checkbox for each client
                        if st.checkbox(matter_info, key=f"simple_{i}"):
                            selected_simple_indices.append(i)
                
                st.write(f"Selected simple matters: {len(selected_simple_indices)}")
            
            with tab3:
                st.subheader("Additional Document Options")
                
                # Check if the template files exist
                before_exists = os.path.exists(BEFORE_DOCX_PATH)
                between_exists = os.path.exists(BETWEEN_DOCX_PATH)
                after_exists = os.path.exists(AFTER_DOCX_PATH)
                
                # Options for including additional pages
                use_before = st.checkbox("Include before pages", value=True, 
                                        help="Insert pages before nominee work highlights",
                                        disabled=not before_exists)
                
                use_between = st.checkbox("Include between pages", value=True, 
                                        help="Insert pages between nominee and simple work highlights",
                                        disabled=not between_exists)
                
                use_after = st.checkbox("Include after pages", value=True, 
                                       help="Insert pages after simple work highlights",
                                       disabled=not after_exists)
                
                # Add watermark info
                st.info("Watermarks from template documents will be preserved in the final output.")
                
                # Warning messages if template files don't exist
                if not before_exists and use_before:
                    st.warning(f"Before pages template not found at {BEFORE_DOCX_PATH}")
                
                if not between_exists and use_between:
                    st.warning(f"Between pages template not found at {BETWEEN_DOCX_PATH}")
                
                if not after_exists and use_after:
                    st.warning(f"After pages template not found at {AFTER_DOCX_PATH}")
            
            # Process forms button
            if st.button("Generate Selected Forms"):
                if len(selected_nominee_indices) == 0 and len(selected_simple_indices) == 0:
                    st.error("Please select at least one matter to proceed.")
                else:
                    # Show progress
                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    
                    status_text.text("Processing selected matters...")
                    progress_bar.progress(25)
                    
                    # Process forms with additional page options
                    output_path = process_benchmark_forms(
                        excel_file, 
                        selected_nominee_indices, 
                        selected_simple_indices,
                        use_before if before_exists else False,
                        use_between if between_exists else False,
                        use_after if after_exists else False
                    )
                    
                    progress_bar.progress(75)
                    
                    if output_path and os.path.exists(output_path):
                        progress_bar.progress(100)
                        status_text.text("Forms generated successfully!")
                        
                        total_forms = len(selected_nominee_indices) + len(selected_simple_indices)
                        st.success(f"Generated forms for {total_forms} selected matters with watermarks preserved!")
                        
                        # Provide download link
                        with open(output_path, "rb") as f:
                            st.download_button(
                                label="Download Combined Forms",
                                data=f,
                                file_name="AsiaLaw_Awards_2025_Submissions.docx",
                                mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                            )
                    else:
                        progress_bar.progress(100)
                        st.error("Failed to generate forms.")
        else:
            st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")

if __name__ == "__main__":
    app()   in this  we have only six practice area Alternate Dispute Resolution
Litigation
Corporate and Allied Laws
Intellectual Property Rights
Indirect Tax, Customs & Trade
Insolvency and Bankruptcy Code
    i want after ypaloding excel add one more field to choose one out of these field for the execl and then fill tht same in all the pratice area fileld whhile filling the rows