from typing import Any, List, Optional from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from app import crud from app.api import deps from app.schemas.block import Block, BlockList from app.schemas.transaction import Transaction, TransactionList router = APIRouter() @router.get("/", response_model=BlockList) def read_blocks( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100 ) -> Any: """ Retrieve blocks with pagination. """ blocks = crud.block.get_multi(db, skip=skip, limit=limit) total = crud.block.get_count(db) return {"blocks": blocks, "total": total} @router.get("/latest", response_model=List[Block]) def read_latest_blocks( db: Session = Depends(deps.get_db), limit: int = Query(20, ge=1, le=100) ) -> Any: """ Retrieve the latest blocks. """ blocks = crud.block.get_latest_blocks(db, limit=limit) return blocks @router.get("/{block_id}", response_model=Block) def read_block( block_id: int, db: Session = Depends(deps.get_db), ) -> Any: """ Get a specific block by id. """ block = crud.block.get(db, id=block_id) if not block: raise HTTPException(status_code=404, detail="Block not found") return block @router.get("/height/{height}", response_model=Block) def read_block_by_height( height: int, db: Session = Depends(deps.get_db), ) -> Any: """ Get a specific block by height. """ block = crud.block.get_by_height(db, height=height) if not block: raise HTTPException(status_code=404, detail="Block not found") return block @router.get("/hash/{block_hash}", response_model=Block) def read_block_by_hash( block_hash: str, db: Session = Depends(deps.get_db), ) -> Any: """ Get a specific block by hash. """ block = crud.block.get_by_hash(db, block_hash=block_hash) if not block: raise HTTPException(status_code=404, detail="Block not found") return block @router.get("/{block_id}/transactions", response_model=TransactionList) def read_block_transactions( block_id: int, db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100 ) -> Any: """ Get transactions for a specific block. """ block = crud.block.get(db, id=block_id) if not block: raise HTTPException(status_code=404, detail="Block not found") transactions = crud.transaction.get_by_block(db, block_id=block_id, skip=skip, limit=limit) total = crud.transaction.get_by_block_count(db, block_id=block_id) return {"transactions": transactions, "total": total}