"""Example: Manual service integration with health checks and usage tracking."""

import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from vikdata import VikdataClient, VikdataMiddleware, UsageReporter
from vikdata.health import HealthChecker


# Mock database and cache connections
class MockDatabase:
    async def execute(self, query: str):
        """Mock database query."""
        await asyncio.sleep(0.01)
        return True


class MockRedis:
    async def ping(self):
        """Mock redis ping."""
        await asyncio.sleep(0.01)
        return True


# Initialize components
db = MockDatabase()
redis = MockRedis()

# Initialize vikdata client
client = VikdataClient(
    base_url="http://localhost:8000",
    service_key="your-service-key",
)

# Create usage reporter
usage_reporter = UsageReporter(
    client=client,
    service="example-service",
    batch_size=50,
    flush_interval=30.0,
)

# Create health checker
health_checker = HealthChecker()


# Health check functions
async def check_database():
    """Check database health."""
    try:
        await db.execute("SELECT 1")
        return True
    except Exception:
        return False


async def check_redis():
    """Check redis health."""
    try:
        await redis.ping()
        return True
    except Exception:
        return False


# Add health checks
health_checker.add_check("database", check_database)
health_checker.add_check("redis", check_redis)


# Lifespan context manager
@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application lifecycle."""
    # Startup
    print("Starting service...")

    async with client:
        # Register service
        registration = await client.services.register(
            name="example-service",
            service_url="http://localhost:8001",
            health_endpoint="/health",
            description="Example microservice with manual integration",
            permissions=["example:read", "example:write"],
        )

        print(f"Service registered: {registration.id}")
        print(f"API Key: {registration.api_key}")

        # Update client with API key
        client.api_key = registration.api_key

        # Start usage tracking
        await usage_reporter.start()

        print("Service started successfully")

        yield

        # Shutdown
        print("Shutting down service...")

        # Stop usage tracking (flushes remaining metrics)
        await usage_reporter.stop()

        # Unregister service
        await client.services.unregister(registration.id)

        print("Service shutdown complete")


# Create FastAPI app
app = FastAPI(
    title="Example Service",
    description="Example microservice with manual vikdata integration",
    lifespan=lifespan,
)

# Add vikdata middleware
app.add_middleware(
    VikdataMiddleware,
    client=client,
    usage_reporter=usage_reporter,
    exclude_paths=["/health", "/metrics"],
)


# Routes
@app.get("/")
async def root():
    """Root endpoint."""
    return {"message": "Example service is running"}


@app.get("/items")
async def list_items(request: Request):
    """List items endpoint."""
    # Access user info from JWT claims (set by middleware)
    tenant_id = request.state.tenant_id
    user_id = request.state.user_id

    return {
        "items": ["item1", "item2", "item3"],
        "tenant_id": tenant_id,
        "user_id": user_id,
    }


@app.post("/items")
async def create_item(item: dict, request: Request):
    """Create item endpoint."""
    tenant_id = request.state.tenant_id

    return {
        "item": item,
        "created": True,
        "tenant_id": tenant_id,
    }


@app.get("/health")
async def health_endpoint():
    """Health check endpoint."""
    result = await health_checker.check()

    # Return 503 if unhealthy
    status_code = 200 if result["status"] == "healthy" else 503

    return JSONResponse(result, status_code=status_code)


@app.get("/metrics")
async def metrics():
    """Basic metrics endpoint."""
    health_status = health_checker.get_status()
    last_check = health_checker.get_last_check_time()

    return {
        "health": health_status,
        "last_health_check": last_check.isoformat() if last_check else None,
        "checks": health_checker.get_checks(),
    }


if __name__ == "__main__":
    import uvicorn

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