import sys
import os
import pandas as pd
from datetime import date

# Add project root to path
sys.path.append(os.path.abspath("/Users/pedroparis/Antigravity Projects/Allostan Labs/risklabs"))

# Import HRAM Strategy Logic
from hram_core import run_live_plan_cash_only

from risklabs.client import create_strategy, analyze
from risklabs.reporting import RiskReport

def run_hram_demo():
    print("==========================================")
    print("Running HRAM-Core Strategy Engine...")
    print("==========================================")
    
    # Run the HRAM strategy to get target weights
    # Note: run_live_plan_cash_only downloads data internally.
    target_weights, _, _, _ = run_live_plan_cash_only(cash_usd=10_000.0, use_ml=True)
    
    print("\n==========================================")
    print("Constructing RiskLab Strategy...")
    print("==========================================")
    
    # Convert Pandas Series to List of Dicts
    # target_weights index is ticker, value is weight
    allocations = []
    
    # Sort by weight desc
    sorted_weights = target_weights.sort_values(ascending=False)
    
    for ticker, weight in sorted_weights.items():
        if weight > 0.001: # Filter tiny residual weights
            allocations.append({"ticker": ticker, "weight": float(weight)})
            
    if not allocations:
        print("Error: No allocations generated by HRAM strategy.")
        return

    # Create Strategy Object
    strategy = create_strategy("HRAM-Core v3.2.1", allocations)
    print(f"Strategy Created with {len(allocations)} positions.")
    for p in allocations[:5]:
        print(f"  - {p['ticker']}: {p['weight']:.2%}")
    if len(allocations) > 5: print("  ... and more")
    
    print("\n==========================================")
    print("Running RiskLab Robustness Analysis...")
    print("==========================================")
    
    try:
        report = analyze(strategy)
        print("Analysis Complete.")
        
        output_file = "/Users/pedroparis/Antigravity Projects/Allostan Labs/risklabs/hram_report.html"
        report.to_file(output_file)
        print(f"\nSUCCESS! Report generated at: {output_file}")
        
    except Exception as e:
        print(f"ERROR during analysis: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    run_hram_demo()
