#!/usr/bin/env python3
"""
AI Energy CLI - Command Line Interface for AI Energy Impact Analysis
Provides easy access to energy analysis and sustainability insights.

Author: Justin Murry
Organization: unparty LLC
License: MIT
LLM: Claude Code
"""

import sys
import os
import argparse
from pathlib import Path

# Make sibling modules importable whether invoked as `python ai/ai_energy_cli.py`
# or from another working directory.
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

try:
    from ai_energy_impact_analyzer import (
        AIEnergyImpactAnalyzer,
        show_unparty_banner,
        brand,
        brand_divider,
    )
    from ai_energy_dashboard_integrator import AIEnergyDashboardIntegrator
except ImportError as e:
    print(f"❌ Import error: {e}")
    print("Make sure you're running from the repository root or the ai/ directory")
    sys.exit(1)

# Reports are written next to the repo root's docs/ directory, resolved
# relative to this file so the CLI works from any working directory.
DOCS_DIR = Path(__file__).resolve().parent.parent / 'docs'

# Brand styling (palette, animated wordmark, tagline) lives in
# ai_energy_impact_analyzer.py and is imported above — this CLI already
# depends on that module for AIEnergyImpactAnalyzer, so sharing the brand
# helpers from there avoids two copies drifting apart. See that file for
# the implementation and why it's not sourced from unparty_styles.sh.


def cmd_analyze(args):
    """Run energy impact analysis"""
    print("🌱 Running AI Energy Impact Analysis...")
    
    analyzer = AIEnergyImpactAnalyzer()
    report = analyzer.generate_report()
    
    if report:
        summary = report['energy_summary']
        tax = report['energy_tax_calculation']
        
        print(brand("\n📊 STATS.:"))
        print(f"CONSUME.: {summary['total_energy_consumption_kwh']:.4f} kWh")
        print(f"FOOTPRINT.: {summary['total_carbon_footprint_kg']:.4f} kg CO2")
        print(f"COST.: ${summary['total_energy_cost_usd']:.4f}")
        print(f"TAX.: ${tax['final_energy_tax_usd']:.4f}")
        print(f"EFFICIENCY.: {summary['average_cache_efficiency_percent']:.1f}%")
        print(f"ANALYZED.: {report['analysis_metadata']['total_sessions_analyzed']}")
    
    return True


def cmd_dashboard(args):
    """CREATE."""
    print("📊 ENERGY DASH...")
    
    integrator = AIEnergyDashboardIntegrator()
    dashboard = integrator.create_energy_dashboard_summary()
    
    if dashboard:
        impact = dashboard['comprehensive_ai_impact']
        
        print(brand("\n💰 AI INVESTMENT:"))
        print(f"API Costs: ${impact['financial_metrics']['direct_api_cost_usd']:.2f}")
        print(f"Energy Costs: ${impact['financial_metrics']['energy_cost_usd']:.2f}")
        print(f"Energy Tax: ${impact['financial_metrics']['energy_tax_usd']:.2f}")
        print(f"Total: ${impact['financial_metrics']['total_ai_cost_usd']:.2f}")
        
        print(brand("\n🌍 Environmental Impact:"))
        print(f"Energy: {impact['environmental_metrics']['total_energy_kwh']:.4f} kWh")
        print(f"Carbon: {impact['environmental_metrics']['carbon_footprint_kg']:.4f} kg CO2")
        print(f"Cache Efficiency: {impact['environmental_metrics']['cache_efficiency_percent']:.1f}%")
        
        print(f"\n🎯 Recommendations: {len(dashboard['sustainability_recommendations'])} opportunities")
    
    return True


def cmd_quick(args):
    """Quick energy summary"""
    print("⚡ Quick Energy Summary...")
    
    # Try to load latest analysis
    docs_dir = DOCS_DIR
    energy_files = list(docs_dir.glob('ai_energy_impact_analysis_*.json'))
    
    if energy_files:
        import json
        latest_file = max(energy_files, key=lambda f: f.stat().st_mtime)
        
        with open(latest_file, 'r') as f:
            data = json.load(f)
        
        summary = data['energy_summary']
        tax = data['energy_tax_calculation']
        
        print(f"📊 Energy: {summary['total_energy_consumption_kwh']:.2f} kWh")
        print(f"🌍 Carbon: {summary['total_carbon_footprint_kg']:.2f} kg CO2") 
        print(f"💰 Cost: ${summary['total_energy_cost_usd']:.2f}")
        print(f"🔋 Tax: ${tax['final_energy_tax_usd']:.2f}")
        print(f"⚡ Cache: {summary['average_cache_efficiency_percent']:.1f}%")
        print(f"📅 From: {latest_file.name}")
    else:
        print("❌ No energy analysis found. Run 'ai-energy analyze' first.")
        return False
    
    return True


def cmd_recommendations(args):
    """Show sustainability recommendations"""
    print("🎯 Sustainability Recommendations...")
    
    # Load latest dashboard integration
    docs_dir = DOCS_DIR
    dashboard_files = list(docs_dir.glob('ai_energy_dashboard_integration_*.json'))
    
    if dashboard_files:
        import json
        latest_file = max(dashboard_files, key=lambda f: f.stat().st_mtime)
        
        with open(latest_file, 'r') as f:
            data = json.load(f)
        
        recommendations = data['sustainability_recommendations']
        
        for i, rec in enumerate(recommendations, 1):
            print(f"\n{i}. {rec['category']}")
            print(f"   Impact: {rec['impact']}")
            print(f"   {rec['recommendation']}")
            
            if 'potential_savings' in rec:
                savings = rec['potential_savings']
                print(f"   Savings: {savings.get('energy_kwh', 0):.2f} kWh, ${savings.get('cost_usd', 0):.2f}, {savings.get('carbon_kg', 0):.2f} kg CO2")
    else:
        print("❌ No dashboard data found. Run 'ai-energy dashboard' first.")
        return False
    
    return True


def cmd_models(args):
    """Show model energy efficiency comparison"""
    print("🔋 Model Energy Efficiency Comparison...")
    
    analyzer = AIEnergyImpactAnalyzer()
    
    print(brand("\nEnergy Consumption (Wh per 1M tokens):"))
    print("Model                          Input    Output   Cache Read   Cache Write")
    print(brand_divider(75))
    
    for model, profile in analyzer.model_energy_consumption.items():
        model_short = model.replace('claude-', '').replace('-20240620', '').replace('-20241022', '')
        input_wh = profile['input_wh_per_1m_tokens']
        output_wh = profile['output_wh_per_1m_tokens']
        cache_read = input_wh * profile['cache_read_multiplier']
        cache_write = input_wh * profile['cache_write_multiplier']
        
        print(f"{model_short:<30} {input_wh:>6.1f}   {output_wh:>6.1f}      {cache_read:>6.1f}       {cache_write:>6.1f}")
    
    print("\nEfficiency Tips:")
    print("• Use Haiku for simple tasks (lowest energy consumption)")
    print("• Maximize cache usage (cache reads cost ~10% of fresh input)")
    print("• Consider output length (generation costs ~10x input processing)")
    
    return True


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="AI Energy Impact Analysis CLI",
        prog="ai-energy"
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Analyze command
    analyze_parser = subparsers.add_parser('analyze', help='Run full energy impact analysis')
    analyze_parser.set_defaults(func=cmd_analyze)
    
    # Dashboard command  
    dashboard_parser = subparsers.add_parser('dashboard', help='Create integrated energy dashboard')
    dashboard_parser.set_defaults(func=cmd_dashboard)
    
    # Quick command
    quick_parser = subparsers.add_parser('quick', help='Show quick energy summary')
    quick_parser.set_defaults(func=cmd_quick)
    
    # Recommendations command
    rec_parser = subparsers.add_parser('recommendations', help='Show sustainability recommendations')
    rec_parser.set_defaults(func=cmd_recommendations)
    
    # Models command
    models_parser = subparsers.add_parser('models', help='Compare model energy efficiency')
    models_parser.set_defaults(func=cmd_models)
    
    # Parse arguments
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return 1

    show_unparty_banner()

    try:
        success = args.func(args)
        return 0 if success else 1
    except Exception as e:
        print(f"❌ Error: {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())