# Simple Loan Calculator — Generated Backend

## Overview

This is a **FastAPI-based backend** for the Simple Loan Calculator application. It provides REST APIs for calculating loan payment schedules, monthly payments, and total interest costs based on loan parameters.

**Key Features:**
- Calculate monthly payments using standard amortization formulas
- Generate complete amortization schedules with payment breakdowns
- Support for principal amounts up to $100,000,000
- Flexible loan terms from 1 to 360 months
- Interest rates from 0% to 30% with precise calculations
- Anonymous access (no authentication required)

**Technology Stack:**
- FastAPI (Python web framework)
- SQLAlchemy (ORM)
- Pydantic (data validation)
- SQLite (default database, easily replaceable)

## Requirements

- **Python 3.11+**
- **uv** (Python package installer and environment manager)

## Install uv

Install `uv` using the official installer:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

Clone or navigate to the project directory, then install all dependencies:

```bash
uv sync
```

This will:
- Create a virtual environment
- Install FastAPI, SQLAlchemy, Uvicorn, and all required dependencies
- Set up the project for immediate use

## Run the Backend

Start the development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at **http://localhost:8000**

You should see output similar to:
```
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

## API Docs

FastAPI automatically generates interactive API documentation:

- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc

Use these interfaces to explore all available endpoints, view request/response schemas, and test API calls directly from your browser.

## OpenAPI JSON

The OpenAPI specification is available at:

**http://localhost:8000/openapi.json**

This JSON file can be imported into tools like Postman, Insomnia, or used to generate client SDKs.

## Project Files

```
.
├── main.py                          # FastAPI application entry point
├── models.py                        # SQLAlchemy database models
├── schemas.py                       # Pydantic request/response schemas
├── database.py                      # Database configuration and session management
├── pyproject.toml                   # Project dependencies and configuration
├── uv.lock                          # Locked dependency versions
└── README.md                        # This file
```

## Example Workflow

### 1. Create a Loan Calculation

Calculate a $250,000 loan at 6.5% APR for 30 years (360 months):

```bash
curl -X POST http://localhost:8000/calculations \
  -H "Content-Type: application/json" \
  -d '{
    "principal": 250000.00,
    "annual_interest_rate": 6.5,
    "loan_term_months": 360,
    "start_date": "2024-02-01"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "principal": 250000.00,
  "annual_interest_rate": 6.5,
  "loan_term_months": 360,
  "monthly_payment": 1580.17,
  "total_interest": 318861.20,
  "total_amount_paid": 568861.20,
  "calculation_method": "standard_amortization",
  "start_date": "2024-02-01",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

### 2. Get Calculation Summary

Retrieve the calculation without the full amortization schedule:

```bash
curl http://localhost:8000/calculations/550e8400-e29b-41d4-a716-446655440000
```

### 3. Get Full Calculation with Amortization Schedule

Retrieve the calculation including all 360 payment entries:

```bash
curl http://localhost:8000/calculations/550e8400-e29b-41d4-a716-446655440000/details
```

**Response includes:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "principal": 250000.00,
  "monthly_payment": 1580.17,
  "total_interest": 318861.20,
  "amortization_schedule_entries": [
    {
      "payment_number": 1,
      "payment_date": "2024-02-01",
      "beginning_balance": 250000.00,
      "payment_amount": 1580.17,
      "principal_payment": 226.84,
      "interest_payment": 1353.33,
      "ending_balance": 249773.16,
      "cumulative_interest": 1353.33
    },
    {
      "payment_number": 2,
      "payment_date": "2024-03-01",
      "beginning_balance": 249773.16,
      "payment_amount": 1580.17,
      "principal_payment": 228.07,
      "interest_payment": 1352.10,
      "ending_balance": 249545.09,
      "cumulative_interest": 2705.43
    }
    // ... 358 more entries
  ]
}
```

### 4. List All Calculations

Get paginated list of all calculations:

```bash
curl "http://localhost:8000/calculations?skip=0&limit=10"
```

### 5. Delete a Calculation

Remove a calculation and all its amortization schedule entries:

```bash
curl -X DELETE http://localhost:8000/calculations/550e8400-e29b-41d4-a716-446655440000
```

## Next Steps

This generated backend provides a solid foundation. Consider these improvements for production:

### 1. **Database Persistence**
- Replace SQLite with PostgreSQL, MySQL, or another production database
- Configure connection pooling and timeouts
- Implement database migrations using Alembic
- Add database indexes for performance optimization

### 2. **Authentication & Authorization**
- Implement user authentication (JWT, OAuth2, etc.)
- Add user ownership to calculations
- Restrict deletion to calculation owners
- Add rate limiting to prevent abuse

### 3. **Code Organization**
- Split `main.py` into separate routers (`routers/calculations.py`)
- Extract business logic into service modules (`services/loan_calculator.py`)
- Separate model definitions (`models/calculation.py`, `models/amortization.py`)
- Create a dedicated `schemas/` directory for request/response models

### 4. **Testing**
- Write unit tests for calculation logic (pytest)
- Add integration tests for API endpoints
- Implement test fixtures and factories
- Set up continuous integration (CI) pipeline
- Aim for 80%+ code coverage

### 5. **Additional Features**
- Add input validation error messages with detailed feedback
- Implement CSV export for amortization schedules
- Add calculation comparison endpoints
- Create background tasks for large calculations
- Add caching for frequently accessed calculations
- Implement logging and monitoring (structured logs, metrics)

### 6. **Documentation**
- Add docstrings to all functions and classes
- Create API usage examples for frontend integration
- Document business rules and formulas
- Add architecture diagrams

### 7. **Deployment**
- Containerize with Docker
- Set up environment-based configuration
- Configure CORS for frontend domains
- Add health check endpoints
- Implement graceful shutdown handling

---

**Ready to calculate!** 🚀

For questions or issues, refer to the interactive API documentation at http://localhost:8000/docs
