# ==========================================
# examples/basic_usage.py
# ==========================================
"""
Basic usage examples for pyCorpFin library
This demonstrates all core functionality without AI frameworks
"""

from pyCorpFin import (
    IRR,
    calculate_mirr,
    calculate_xirr,
    presentValue,
    futureValue,
    emi,
    annuity
)
from datetime import datetime


def example_irr():
    """Example: Calculate Internal Rate of Return"""
    print("=" * 60)
    print("IRR (Internal Rate of Return) Example")
    print("=" * 60)

    # Investment: $10,000 upfront, returns $3,000 per year for 4 years
    cashflows = [-10000, 3000, 3000, 3000, 3000]

    result = IRR(cashflows)

    if isinstance(result, str):
        print(f"Error: {result}")
    else:
        print(f"Cash flows: {cashflows}")
        print(f"IRR: {result:.4%} (or {result:.6f} as decimal)")
        print(f"Interpretation: This investment yields {result:.2%} annual return")
    print()


def example_mirr():
    """Example: Calculate Modified Internal Rate of Return"""
    print("=" * 60)
    print("MIRR (Modified Internal Rate of Return) Example")
    print("=" * 60)

    cashflows = [-10000, 3000, 3000, 3000, 3000]
    finance_rate = 0.10  # Cost of capital: 10%
    reinvest_rate = 0.08  # Reinvestment rate: 8%

    result = calculate_mirr(cashflows, finance_rate, reinvest_rate)

    if isinstance(result, str):
        print(f"Error: {result}")
    else:
        print(f"Cash flows: {cashflows}")
        print(f"Finance rate: {finance_rate:.2%}")
        print(f"Reinvestment rate: {reinvest_rate:.2%}")
        print(f"MIRR: {result:.4%}")
        print(f"Interpretation: More realistic return considering reinvestment at {reinvest_rate:.0%}")
    print()


def example_xirr():
    """Example: Calculate Extended IRR for irregular dates"""
    print("=" * 60)
    print("XIRR (Extended Internal Rate of Return) Example")
    print("=" * 60)

    # Irregular investment schedule
    cashflows = [-10000, 3000, 4000, 5000]
    dates = [
        datetime(2023, 1, 15),  # Initial investment
        datetime(2023, 7, 10),  # First return (6 months)
        datetime(2024, 2, 20),  # Second return (13 months)
        datetime(2024, 10, 5)  # Final return (21 months)
    ]

    result = calculate_xirr(cashflows, dates)

    if isinstance(result, str):
        print(f"Error: {result}")
    else:
        print("Cash flows with dates:")
        for cf, dt in zip(cashflows, dates):
            print(f"  {dt.strftime('%Y-%m-%d')}: ${cf:,.0f}")
        print(f"\nXIRR: {result:.4%}")
        print(f"Interpretation: Annualized return for irregular cash flows")
    print()


def example_present_value():
    """Example: Calculate Present Value (NPV)"""
    print("=" * 60)
    print("Present Value (NPV) Example")
    print("=" * 60)

    # Future cash flows
    cashflows = [1000, 2000, 3000, 4000]  # Years 0-3
    discount_rate = 0.10  # 10% discount rate

    cf_dict = {i: cashflows[i] for i in range(len(cashflows))}
    result = presentValue(cf_dict, discount_rate, len(cashflows) - 1)

    print(f"Future cash flows: {cashflows}")
    print(f"Discount rate: {discount_rate:.2%}")
    print(f"Present Value: ${result:,.2f}")
    print(f"Interpretation: These future cash flows are worth ${result:,.2f} today")
    print()


def example_future_value():
    """Example: Calculate Future Value"""
    print("=" * 60)
    print("Future Value Example")
    print("=" * 60)

    # Current investments
    cashflows = [1000, 2000, 3000]  # Years 0-2
    interest_rate = 0.08  # 8% annual interest

    cf_dict = {i: cashflows[i] for i in range(len(cashflows))}
    result = futureValue(cf_dict, interest_rate, len(cashflows) - 1)

    print(f"Current investments: {cashflows}")
    print(f"Interest rate: {interest_rate:.2%}")
    print(f"Future Value: ${result:,.2f}")
    print(f"Interpretation: These investments will grow to ${result:,.2f}")
    print()


def example_emi():
    """Example: Calculate Loan EMI"""
    print("=" * 60)
    print("EMI (Equated Monthly Installment) Example")
    print("=" * 60)

    principal = 500000  # $500,000 home loan
    annual_rate = 0.075  # 7.5% annual interest
    years = 30
    months = years * 12

    monthly_rate = annual_rate / 12
    monthly_payment = emi(principal, monthly_rate, months)

    total_payment = monthly_payment * months
    total_interest = total_payment - principal

    print(f"Loan amount: ${principal:,.2f}")
    print(f"Annual interest rate: {annual_rate:.2%}")
    print(f"Loan tenure: {years} years ({months} months)")
    print(f"\nMonthly EMI: ${monthly_payment:,.2f}")
    print(f"Total payment: ${total_payment:,.2f}")
    print(f"Total interest: ${total_interest:,.2f}")
    print(f"Interest as % of principal: {(total_interest / principal) * 100:.1f}%")
    print()


def example_annuity():
    """Example: Calculate Annuity Payment"""
    print("=" * 60)
    print("Annuity Payment Example")
    print("=" * 60)

    present_value = 100000  # $100,000 to be paid out
    annual_rate = 0.06  # 6% annual return
    years = 20

    annual_payment = annuity(present_value, annual_rate, years)
    total_payments = annual_payment * years
    total_interest = total_payments - present_value

    print(f"Present value: ${present_value:,.2f}")
    print(f"Annual return rate: {annual_rate:.2%}")
    print(f"Period: {years} years")
    print(f"\nAnnual payment: ${annual_payment:,.2f}")
    print(f"Total payments: ${total_payments:,.2f}")
    print(f"Total interest earned: ${total_interest:,.2f}")
    print()


def example_comparison():
    """Example: Compare different investment scenarios"""
    print("=" * 60)
    print("Investment Comparison Example")
    print("=" * 60)

    # Two investment options
    option_a = [-10000, 2000, 3000, 4000, 5000]
    option_b = [-10000, 5000, 4000, 3000, 2000]

    irr_a = IRR(option_a)
    irr_b = IRR(option_b)

    discount_rate = 0.10
    cf_dict_a = {i: option_a[i] for i in range(len(option_a))}
    cf_dict_b = {i: option_b[i] for i in range(len(option_b))}

    npv_a = presentValue(cf_dict_a, discount_rate, len(option_a) - 1)
    npv_b = presentValue(cf_dict_b, discount_rate, len(option_b) - 1)

    print("Option A - Increasing returns:")
    print(f"  Cash flows: {option_a}")
    print(f"  IRR: {irr_a:.4%}")
    print(f"  NPV at {discount_rate:.0%}: ${npv_a:,.2f}")
    print()

    print("Option B - Decreasing returns:")
    print(f"  Cash flows: {option_b}")
    print(f"  IRR: {irr_b:.4%}")
    print(f"  NPV at {discount_rate:.0%}: ${npv_b:,.2f}")
    print()

    print("Comparison:")
    print(f"  Option A has {'higher' if irr_a > irr_b else 'lower'} IRR")
    print(f"  Option B has {'higher' if npv_b > npv_a else 'lower'} NPV at {discount_rate:.0%}")
    print("  Note: Option B receives money earlier, creating higher present value!")
    print()


def main():
    """Run all examples"""
    print("\n" + "=" * 60)
    print("PYCORPFIN - Basic Usage Examples")
    print("=" * 60 + "\n")

    example_irr()
    example_mirr()
    example_xirr()
    example_present_value()
    example_future_value()
    example_emi()
    example_annuity()
    example_comparison()

    print("=" * 60)
    print("All examples completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()
