#!/usr/bin/env python3
"""
Step 6: Report Context Preparation
Aggregates all analysis results, figure paths, and thesis points into a single
structured JSON file for the downstream report generation workflow.
"""

import json
import os
from pathlib import Path
from datetime import datetime

# Define paths
SESSION_DIR = Path("/app/sandbox/session_20260203_085912_030e6e80a419")
RESULTS_DIR = SESSION_DIR / "results"
FIGURES_DIR = SESSION_DIR / "figures"

print("=" * 60)
print("STEP 6: REPORT CONTEXT PREPARATION")
print("=" * 60)
print(f"Timestamp: {datetime.now().isoformat()}")
print()

# 1. Read all summary files
print("1. Reading summary files...")

def read_file_content(filepath):
    """Read file content safely."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        print(f"   WARNING: Could not read {filepath}: {e}")
        return ""

# Read summary files
financial_summary = read_file_content(RESULTS_DIR / "financial_health_summary.txt")
print(f"   - financial_health_summary.txt: {len(financial_summary)} chars")

valuation_summary = read_file_content(RESULTS_DIR / "valuation_summary.txt")
print(f"   - valuation_summary.txt: {len(valuation_summary)} chars")

sentiment_analysis = read_file_content(RESULTS_DIR / "sentiment_analysis.txt")
print(f"   - sentiment_analysis.txt: {len(sentiment_analysis)} chars")

investment_thesis = read_file_content(RESULTS_DIR / "investment_thesis_synthesis.txt")
print(f"   - investment_thesis_synthesis.txt: {len(investment_thesis)} chars")

# Read thesis summary JSON
print("\n2. Reading thesis_summary.json...")
try:
    with open(RESULTS_DIR / "thesis_summary.json", 'r') as f:
        thesis_summary_json = json.load(f)
    print(f"   - Loaded {len(thesis_summary_json)} key metrics")
except Exception as e:
    print(f"   WARNING: Could not read thesis_summary.json: {e}")
    thesis_summary_json = {}

# 3. Scan figures directory
print("\n3. Scanning figures/ directory...")
figures_list = []
figure_mapping = {
    "revenue_profit_trend.png": {
        "caption": "Revenue vs Net Income Trend (2021-2024)",
        "relevance": "Shows accelerating revenue decline and profit margin collapse",
        "section": "financial"
    },
    "margin_erosion.png": {
        "caption": "Operating and Net Profit Margin Erosion",
        "relevance": "Illustrates margin compression from +10% to -135%",
        "section": "financial"
    },
    "cash_vs_debt.png": {
        "caption": "Cash Position vs Total Debt Evolution",
        "relevance": "Demonstrates aggressive deleveraging despite revenue decline",
        "section": "financial"
    },
    "projected_revenue_scenarios.png": {
        "caption": "DCF Revenue Projections: Bull/Base/Bear Scenarios",
        "relevance": "Visual comparison of valuation scenario outcomes",
        "section": "valuation"
    },
    "valuation_sensitivity.png": {
        "caption": "Valuation Sensitivity to WACC and Growth Assumptions",
        "relevance": "Shows fair value range across different assumptions",
        "section": "valuation"
    },
    "technical_chart.png": {
        "caption": "Technical Analysis: Price, Moving Averages, and Volume",
        "relevance": "Confirms strong downtrend with price below key SMAs",
        "section": "valuation"
    },
    "ownership_structure.png": {
        "caption": "Ownership Structure and Short Interest Breakdown",
        "relevance": "Shows 5.9% short interest - trade not crowded",
        "section": "sentiment"
    }
}

if FIGURES_DIR.exists():
    for fig_file in sorted(FIGURES_DIR.iterdir()):
        if fig_file.suffix in ['.png', '.jpg', '.jpeg', '.pdf', '.svg']:
            fig_name = fig_file.name
            fig_info = figure_mapping.get(fig_name, {
                "caption": fig_name.replace('_', ' ').replace('.png', '').title(),
                "relevance": "Analysis visualization",
                "section": "general"
            })
            figures_list.append({
                "path": f"figures/{fig_name}",
                "filename": fig_name,
                "caption": fig_info["caption"],
                "relevance": fig_info["relevance"],
                "section": fig_info["section"]
            })
            print(f"   - {fig_name}: {fig_info['caption']}")
else:
    print("   WARNING: figures/ directory not found")

print(f"\n   Total figures found: {len(figures_list)}")

# 4. Build structured JSON object
print("\n4. Building structured JSON report context...")

report_context = {
    "metadata": {
        "generated_at": datetime.now().isoformat(),
        "ticker": "CHGG",
        "company": "Chegg, Inc.",
        "analysis_type": "Investment Thesis - Short Position",
        "workflow_status": "Analysis Complete - Ready for Writing Agent",
        "steps_completed": [
            "Step 1: Environment Setup & Data Inventory",
            "Step 2: Financial Health Analysis",
            "Step 3: Valuation Modeling",
            "Step 4: Sentiment & Short Interest Analysis",
            "Step 5: Investment Thesis Synthesis",
            "Step 6: Report Context Preparation"
        ]
    },
    "thesis_core": investment_thesis,
    "key_metrics": thesis_summary_json,
    "section_summaries": {
        "financial_health": {
            "title": "Financial Health Analysis",
            "content": financial_summary,
            "key_findings": [
                "Revenue declined 42% from 2021 peak ($776M) to TTM ($448M)",
                "Net profit margin collapsed to -135.5% in 2024",
                "$677M goodwill impairment acknowledges permanent AI disruption",
                "Current ratio < 1.0 indicates short-term liquidity stress",
                "Aggressive debt reduction from $1.7B to $504M"
            ]
        },
        "valuation": {
            "title": "Valuation Analysis",
            "content": valuation_summary,
            "key_findings": [
                "Probability-weighted fair value: $0.94 (+34% vs current)",
                "Liquidation value floor: $0.50/share",
                "Bear case (35% probability): $0.12/share",
                "Reverse DCF implies -35% perpetual growth expectation",
                "Trading at 0.52x book, 0.17x sales (distressed multiples)"
            ]
        },
        "sentiment": {
            "title": "Short Interest & Market Sentiment",
            "content": sentiment_analysis,
            "key_findings": [
                "Short interest at 5.9% - trade NOT crowded",
                "Days to cover: 5.5 days - orderly exit possible",
                "Squeeze risk: MODERATE (score 50/100)",
                "Stock transitioning from 'hated' to 'ignored'",
                "Institutional ownership: ~38% (limited forced selling)"
            ]
        }
    },
    "figures": figures_list,
    "investment_recommendation": {
        "position": "MAINTAIN SHORT",
        "conviction": "HIGH",
        "entry_zone": {
            "low": 0.70,
            "high": 0.90,
            "optimal": 0.89
        },
        "stop_loss": 1.03,
        "price_targets": {
            "base_case": {"price": 0.50, "probability": 0.50, "return_pct": -32},
            "bear_case": {"price": 0.25, "probability": 0.35, "return_pct": -66},
            "extreme_bear": {"price": 0.12, "probability": 0.15, "return_pct": -84}
        },
        "risk_reward_ratio": "1:0.8",
        "position_sizing": "2-3% of portfolio",
        "time_horizon": "6-18 months"
    },
    "key_catalysts": {
        "negative_for_stock": [
            "Q4 2025 / Q1 2026 Earnings: Continued subscriber losses",
            "Guidance Reduction: Management admits further deterioration",
            "Cash Burn Acceleration: If cost cuts fail",
            "AI Competition Intensifies: ChatGPT, Gemini, Claude improvements",
            "Debt Maturity / Refinancing Issues"
        ],
        "cover_triggers": [
            "Strategic Review / M&A Rumor announcement",
            "Short Squeeze (limited potential with 6% SI)"
        ]
    },
    "file_references": {
        "results": [
            "results/financial_health_summary.txt",
            "results/valuation_summary.txt",
            "results/sentiment_analysis.txt",
            "results/investment_thesis_synthesis.txt",
            "results/thesis_summary.json",
            "results/financial_metrics_history.csv",
            "results/valuation_scenarios.csv",
            "results/technical_indicators.csv"
        ],
        "figures": [f["path"] for f in figures_list],
        "data": [
            "data/chegg_cleaned.csv"
        ]
    }
}

# 5. Save the report context JSON
print("\n5. Saving report_context.json...")
output_path = RESULTS_DIR / "report_context.json"
with open(output_path, 'w', encoding='utf-8') as f:
    json.dump(report_context, f, indent=2, ensure_ascii=False)

print(f"   Saved to: {output_path}")
print(f"   File size: {output_path.stat().st_size / 1024:.1f} KB")

# Validate JSON
print("\n6. Validating JSON structure...")
with open(output_path, 'r') as f:
    validated = json.load(f)

required_keys = ['metadata', 'thesis_core', 'key_metrics', 'section_summaries', 'figures']
all_present = all(k in validated for k in required_keys)
print(f"   Required keys present: {all_present}")
print(f"   Total keys: {len(validated)}")
print(f"   Thesis core length: {len(validated['thesis_core'])} chars")
print(f"   Key metrics count: {len(validated['key_metrics'])}")
print(f"   Section summaries: {list(validated['section_summaries'].keys())}")
print(f"   Figures count: {len(validated['figures'])}")

print("\n" + "=" * 60)
print("REPORT CONTEXT PREPARATION COMPLETE")
print("=" * 60)
print(f"\nOutput: results/report_context.json")
print("Status: Ready for Writing Agent ingestion")
