#!/usr/bin/env python3
"""
Script to upload LLM analysis results to S3
"""
import json
import os
import sys
from datetime import datetime

def upload_results():
    try:
        from storage.config import load_config_from_env
        from storage.s3_adapter import S3Storage
        
        if not os.path.exists("llm_analysis_results.json"):
            print("⚠️  No analysis results file found to upload")
            return False
            
        cfg = load_config_from_env()
        s3 = S3Storage(cfg, no_aws=False)
        
        # Read the analysis results
        with open("llm_analysis_results.json", "r") as f:
            results = json.load(f)
        
        # Add metadata
        results["uploaded_at"] = datetime.utcnow().isoformat() + "Z"
        results["workflow_run_id"] = os.environ.get("GITHUB_RUN_NUMBER", "unknown")
        results["workflow_run_url"] = f"{os.environ.get('GITHUB_SERVER_URL', '')}/{os.environ.get('GITHUB_REPOSITORY', '')}/actions/runs/{os.environ.get('GITHUB_RUN_ID', '')}"
        
        # Upload to S3
        s3_key = s3.put_json(cfg.s3_bucket_processed, "llm-analysis", f"analysis-{os.environ.get('GITHUB_RUN_NUMBER', 'unknown')}", results)
        print("✅ Uploaded analysis results to S3: {}".format(s3_key))
        
        # Also create a summary file
        summary = {
            "workflow_run_id": os.environ.get("GITHUB_RUN_NUMBER", "unknown"),
            "analysis_date": results.get("pipeline_metadata", {}).get("created_at"),
            "llm_provider": os.environ.get("LLM_PROVIDER", "unknown"),
            "files_analyzed": results.get("summary", {}).get("total_files_retrieved", 0),
            "successful_batches": results.get("summary", {}).get("successful_llm_batches", 0),
            "total_batches": results.get("summary", {}).get("batches_processed", 0),
            "documents_analyzed": results.get("summary", {}).get("total_documents_analyzed", 0),
            "s3_results_key": s3_key
        }
        
        summary_key = s3.put_json(cfg.s3_bucket_processed, "llm-analysis", f"summary-{os.environ.get('GITHUB_RUN_NUMBER', 'unknown')}", summary)
        print("✅ Uploaded analysis summary to S3: {}".format(summary_key))
        
        return True
        
    except Exception as e:
        print("❌ Failed to upload to S3: {}".format(e))
        return False

if __name__ == "__main__":
    success = upload_results()
    sys.exit(0 if success else 1)
