import os
import sys
import json

def parse_pdf(file_path):
    import pypdf
    reader = pypdf.PdfReader(file_path)
    text_content = []
    text_content.append(f"### [PDF PARSED CONTENT]: {os.path.basename(file_path)}")
    text_content.append(f"**Total Pages**: {len(reader.pages)}")
    
    for idx, page in enumerate(reader.pages):
        page_text = page.extract_text()
        text_content.append(f"--- Page {idx + 1} ---")
        text_content.append(page_text)
    return "\n\n".join(text_content)

def parse_excel(file_path):
    import pandas as pd
    xl = pd.ExcelFile(file_path)
    text_content = []
    text_content.append(f"### [EXCEL PARSED CONTENT]: {os.path.basename(file_path)}")
    text_content.append(f"**Sheet Names**: {', '.join(xl.sheet_names)}")
    
    for sheet in xl.sheet_names:
        text_content.append(f"#### Sheet: {sheet}")
        df = xl.parse(sheet)
        # Handle large sheets by showing top/tail if too large
        if len(df) > 100:
            text_content.append(f"*Note: Sheet is large ({len(df)} rows). Showing preview.*")
            preview_df = df.head(50)
            text_content.append(preview_df.to_markdown(index=False))
            text_content.append("...")
            text_content.append(df.tail(10).to_markdown(index=False))
        else:
            text_content.append(df.to_markdown(index=False))
    return "\n\n".join(text_content)

def parse_csv(file_path):
    import pandas as pd
    df = pd.read_csv(file_path)
    text_content = []
    text_content.append(f"### [CSV PARSED CONTENT]: {os.path.basename(file_path)}")
    text_content.append(f"**Total Rows**: {len(df)} | **Total Columns**: {len(df.columns)}")
    
    if len(df) > 150:
        text_content.append(f"*Note: CSV is large ({len(df)} rows). Showing preview (Head and Tail).*")
        text_content.append(df.head(50).to_markdown(index=False))
        text_content.append("\n...\n")
        text_content.append(df.tail(15).to_markdown(index=False))
    else:
        text_content.append(df.to_markdown(index=False))
    return "\n\n".join(text_content)

def main():
    if len(sys.argv) < 2:
        print(json.dumps({"error": "No file path provided."}))
        return

    file_path = sys.argv[1]
    if not os.path.exists(file_path):
        print(json.dumps({"error": f"File not found: {file_path}"}))
        return

    ext = os.path.splitext(file_path)[1].lower()
    try:
        if ext == '.pdf':
            payload = parse_pdf(file_path)
        elif ext in ['.xlsx', '.xls']:
            payload = parse_excel(file_path)
        elif ext == '.csv':
            payload = parse_csv(file_path)
        else:
            # Fallback to standard reading
            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
            payload = f"### [PARSED CONTENT]: {os.path.basename(file_path)}\n\n{content}"
            
        print(json.dumps({"text_payload": payload}))
    except Exception as e:
        print(json.dumps({"error": f"Error parsing {ext} file: {str(e)}"}))

if __name__ == "__main__":
    main()
