TOOL_NAME = "process_outlook_attachments"
TOOL_DESCRIPTION = """Automatically extracts and analyzes attachments from Outlook emails, including PDFs, Office files, images, and text-based documents."""
TOOL_ARGS = '{"folder_path":{"type":"string","description":"Directory path where attachments should be saved"},"count":{"type":"integer","default":50,"description":"Maximum number of emails to check"},"unread_only":{"type":"boolean","default":false,"description":"Only check unread emails"},"since":{"type":"string","description":"Filter emails received on or after this date (YYYY-MM-DD)"},"sender":{"type":"string","description":"Filter by sender email address (partial match)"},"subject_contains":{"type":"string","description":"Filter by subject containing this text"},"analyze_content":{"type":"boolean","default":true,"description":"Whether to analyze attachments for content and metadata"}}'

import json
import os
from pathlib import Path
from tools._std import tool_ok, tool_error

def run(args: dict) -> str:
    folder_path = args.get("folder_path", "./attachments")
    count = args.get("count", 50)
    unread_only = args.get("unread_only", False)
    since = args.get("since")
    sender = args.get("sender")
    subject_contains = args.get("subject_contains")
    analyze_content = args.get("analyze_content", True)
    
    os.makedirs(folder_path, exist_ok=True)
    
    from tools.extract_email_attachments import run as extract_run
    
    extract_args = {
        "folder_path": folder_path,
        "count": count,
        "unread_only": unread_only
    }
    if since:
        extract_args["since"] = since
    if sender:
        extract_args["sender"] = sender
    if subject_contains:
        extract_args["subject_contains"] = subject_contains
    
    result = extract_run(extract_args)
    
    # extract_email_attachments now returns standardized JSON
    try:
        parsed = json.loads(result)
        if parsed.get("status") == "ok":
            files_data = (parsed.get("data") or {}).get("files", [])
            files = [f["file"] for f in files_data if os.path.exists(f.get("file", ""))]
        else:
            return tool_ok({"files": [], "message": parsed.get("message", "")}, "No attachments found matching criteria")
    except (json.JSONDecodeError, KeyError):
        # Fallback: parse legacy plain-text output
        files = []
        for line in result.splitlines():
            line = line.strip()
            if line and " (" in line and " KB)" in line:
                file_path_str = line.split(" (")[0].strip()
                if os.path.exists(file_path_str):
                    files.append(file_path_str)
    
    if not files:
        return tool_ok({"files": []}, "No attachments found matching criteria")
    
    from tools.analyze_non_pdf_attachments import run as analyze_run
    
    processed = []
    
    for file_path in files:
        ext = Path(file_path).suffix.lower()

        if analyze_content:
            try:
                analysis = analyze_run({
                    "file_path": file_path,
                    "extract_text": True,
                    "extract_metadata": True
                })
                try:
                    analysis_data = json.loads(analysis)
                except Exception:
                    analysis_data = {"output": analysis}

                processed.append({
                    "file": file_path,
                    "type": ext.lstrip('.') if ext else "unknown",
                    "analyzed": True,
                    "analysis": analysis_data
                })
            except Exception as e:
                processed.append({
                    "file": file_path,
                    "type": ext.lstrip('.') if ext else "unknown",
                    "analyzed": False,
                    "error": str(e)
                })
        else:
            processed.append({
                "file": file_path,
                "type": ext.lstrip('.') if ext else "unknown",
                "analyzed": False
            })
    
    return tool_ok({
        "folder": os.path.abspath(folder_path),
        "total_files": len(files),
        "analyzed_count": sum(1 for p in processed if p.get("analyzed")),
        "results": processed
    }, f"Processed {len(files)} attachments, analyzed {sum(1 for p in processed if p.get('analyzed'))}")
