"""
FastAPI application initialization.

Single Responsibility: Wire up dependencies and register routes.
"""

import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from mangum import Mangum

from .clients.dynamodb_client import DynamoDBClient
from .clients.s3_client import S3Client
from .clients.sqs_client import SQSClient
from .routes import health_routes, job_routes
from .services.job_status import JobStatusService
from .services.job_submission import JobSubmissionService


def _load_config() -> tuple[str, str, str, str]:
    """Load and validate environment configuration."""
    region = os.getenv("AWS_REGION", "us-east-1")
    dynamodb_table = os.getenv("DYNAMODB_TABLE_NAME", "czbg-jobs-dev")
    sqs_queue_url = os.getenv("SQS_QUEUE_URL")
    s3_bucket = os.getenv("S3_BUCKET_NAME")

    if not sqs_queue_url:
        raise ValueError("SQS_QUEUE_URL environment variable required")
    if not s3_bucket:
        raise ValueError("S3_BUCKET_NAME environment variable required")

    return region, dynamodb_table, sqs_queue_url, s3_bucket


def _create_clients(
    region: str, dynamodb_table: str, sqs_queue_url: str, s3_bucket: str
) -> tuple[DynamoDBClient, SQSClient, S3Client]:
    """Create AWS service clients."""
    dynamodb_client = DynamoDBClient(dynamodb_table, region)
    sqs_client = SQSClient(sqs_queue_url, region)
    s3_client = S3Client(s3_bucket, region)
    return dynamodb_client, sqs_client, s3_client


def _create_services(
    dynamodb_client: DynamoDBClient, sqs_client: SQSClient, s3_client: S3Client
) -> tuple[JobSubmissionService, JobStatusService]:
    """Create application services with dependency injection."""
    job_submission_service = JobSubmissionService(
        s3_client=s3_client,
        dynamodb_client=dynamodb_client,
        sqs_client=sqs_client,
    )
    job_status_service = JobStatusService(dynamodb_client=dynamodb_client)
    return job_submission_service, job_status_service


def create_app() -> FastAPI:
    """Create and configure FastAPI application."""
    app = FastAPI(
        title="CZBG API",
        description="API for CloudZero Billing Generator job processing",
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc",
    )

    # CORS middleware for CLI access
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # TODO: Restrict in production
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Initialize infrastructure
    region, dynamodb_table, sqs_queue_url, s3_bucket = _load_config()
    dynamodb_client, sqs_client, s3_client = _create_clients(
        region, dynamodb_table, sqs_queue_url, s3_bucket
    )
    job_submission_service, job_status_service = _create_services(
        dynamodb_client, sqs_client, s3_client
    )

    # Wire up and register routes
    job_routes.init_services(job_submission_service, job_status_service)
    app.include_router(health_routes.router)
    app.include_router(job_routes.router)

    return app


# Create app instance
app = create_app()

# Lambda handler (for AWS Lambda deployment)
handler = Mangum(app, lifespan="off")


# Startup/shutdown events
@app.on_event("startup")
async def startup_event():
    """Log startup message."""
    print("CZBG API starting up...")
    print(f"DynamoDB Table: {os.getenv('DYNAMODB_TABLE_NAME')}")
    print(f"SQS Queue: {os.getenv('SQS_QUEUE_URL')}")
    print(f"S3 Bucket: {os.getenv('S3_BUCKET_NAME')}")


@app.on_event("shutdown")
async def shutdown_event():
    """Log shutdown message."""
    print("CZBG API shutting down...")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
