from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.file import File as FileModel
from app.schemas.file import FileCreate, FileUpdate, FileDelete, FileList, FileInDB
from app.models.box import Box as BoxModel, OpenBox as OpenBoxModel
from app.schemas.box import BoxCreate, BoxUpdate, BoxDelete, BoxList, OpenBoxCreate, OpenBoxUpdate, OpenBoxDelete, OpenBoxList, BoxInDB, OpenBoxInDB
from app.models.game import Game as GameModel
from app.schemas.game import GameCreate, GameUpdate, GameDelete, GameList, GameInDB
from app.models.card import Card as CardModel
from app.schemas.card import CardCreate, CardUpdate, CardDelete, CardList, CardInDB
from app.services import CardService, OrderService
from app.services.file_processing_service import FileProcessingService
from app.services.external_api.tcgplayer.tcgplayer_inventory_service import TCGPlayerInventoryService

router = APIRouter(prefix="/api")

# Initialize services
card_service = CardService()
order_service = OrderService()
file_processing_service = FileProcessingService()
tcgplayer_inventory_service = TCGPlayerInventoryService()

# ============================================================================
# Health Check & Root Endpoints
# ============================================================================
@router.get("/")
async def root():
    return {"message": "CCR Cards Management API is running."}

@router.get("/health")
async def health():
    return {"status": "ok"}

# ============================================================================
# Card Management Endpoints
# ============================================================================
@router.get("/cards", response_model=CardList)
async def get_cards(
    db: Session = Depends(get_db),
    page: int = 1,
    limit: int = 10,
    type: str = None,
    id: int = None
):
    skip = (page - 1) * limit
    cards = card_service.get_all(db, skip=skip, limit=limit)
    total = db.query(CardModel).count()
    return {
        "cards": cards,
        "total": total,
        "page": page,
        "limit": limit
    }

@router.post("/cards", response_model=CardInDB)
async def create_card(card: CardCreate, db: Session = Depends(get_db)):
    try:
        created_card = card_service.create(db, card.dict())
        return created_card
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.put("/cards/{card_id}", response_model=CardInDB)
async def update_card(card_id: int, card: CardUpdate, db: Session = Depends(get_db)):
    db_card = card_service.get(db, card_id)
    if not db_card:
        raise HTTPException(status_code=404, detail="Card not found")
    try:
        updated_card = card_service.update(db, db_card, card.dict(exclude_unset=True))
        return updated_card
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/cards/{card_id}", response_model=CardDelete)
async def delete_card(card_id: int, db: Session = Depends(get_db)):
    success = card_service.delete(db, card_id)
    if not success:
        raise HTTPException(status_code=404, detail="Card not found")
    return {"message": "Card deleted successfully"}

# ============================================================================
# Order Management Endpoints
# ============================================================================
@router.post("/orders")
async def create_order(order_data: dict, card_ids: list[int], db: Session = Depends(get_db)):
    try:
        order = order_service.create_order_with_cards(db, order_data, card_ids)
        return order
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/orders")
async def get_orders(
    db: Session = Depends(get_db),
    page: int = 1,
    limit: int = 10
):
    skip = (page - 1) * limit
    orders = order_service.get_orders_with_cards(db, skip=skip, limit=limit)
    return {
        "orders": orders,
        "page": page,
        "limit": limit
    }

# ============================================================================
# File Management Endpoints
# ============================================================================
@router.get("/files", response_model=FileList)
async def get_files(page: int = 1, limit: int = 10, type: str = None, id: int = None):
    return {"files": [], "total": 0, "page": page, "limit": limit}

@router.post("/files", response_model=FileInDB)
async def create_file(file: FileCreate):
    return {"message": "File created successfully"}

@router.put("/files/{file_id}", response_model=FileInDB)
async def update_file(file_id: int, file: FileUpdate):
    return {"message": "File updated successfully"}

@router.delete("/files/{file_id}", response_model=FileDelete)
async def delete_file(file_id: int):
    return {"message": "File deleted successfully"}

# ============================================================================
# Box Management Endpoints
# ============================================================================
@router.get("/boxes", response_model=BoxList)
async def get_boxes(page: int = 1, limit: int = 10, type: str = None, id: int = None):
    return {"boxes": [], "total": 0, "page": page, "limit": limit}

@router.post("/boxes", response_model=BoxInDB)
async def create_box(box: BoxCreate):
    return {"message": "Box created successfully"}

@router.put("/boxes/{box_id}", response_model=BoxInDB)
async def update_box(box_id: int, box: BoxUpdate):
    return {"message": "Box updated successfully"}

@router.delete("/boxes/{box_id}", response_model=BoxDelete)
async def delete_box(box_id: int):
    return {"message": "Box deleted successfully"}

# ============================================================================
# Open Box Management Endpoints
# ============================================================================
@router.get("/open_boxes", response_model=OpenBoxList)
async def get_open_boxes(page: int = 1, limit: int = 10, type: str = None, id: int = None):
    return {"open_boxes": [], "total": 0, "page": page, "limit": limit}

@router.post("/open_boxes", response_model=OpenBoxInDB)
async def create_open_box(open_box: OpenBoxCreate):
    return {"message": "Open box created successfully"}

@router.put("/open_boxes/{open_box_id}", response_model=OpenBoxInDB)
async def update_open_box(open_box_id: int, open_box: OpenBoxUpdate):
    return {"message": "Open box updated successfully"}

@router.delete("/open_boxes/{open_box_id}", response_model=OpenBoxDelete)
async def delete_open_box(open_box_id: int):
    return {"message": "Open box deleted successfully"}

# ============================================================================
# Game Management Endpoints
# ============================================================================
@router.get("/games", response_model=GameList)
async def get_games(page: int = 1, limit: int = 10, type: str = None, id: int = None):
    return {"games": [], "total": 0, "page": page, "limit": limit}

@router.post("/games", response_model=GameInDB)
async def create_game(game: GameCreate):
    return {"message": "Game created successfully"}

@router.put("/games/{game_id}", response_model=GameInDB)
async def update_game(game_id: int, game: GameUpdate):
    return {"message": "Game updated successfully"}

@router.delete("/games/{game_id}", response_model=GameDelete)
async def delete_game(game_id: int):
    return {"message": "Game deleted successfully"}

@router.post("/tcgplayer/process-export")
async def process_tcgplayer_export(export_type: str, db: Session = Depends(get_db)):
    """
    Download and process a TCGPlayer export file.
    
    Args:
        export_type: Type of export to process (staged, live, or pricing)
        db: Database session
    """
    try:
        # Download the file
        file_bytes = await tcgplayer_inventory_service.get_tcgplayer_export(export_type)
        
        # Process the file and load into database
        stats = await file_processing_service.process_tcgplayer_export(db, file_bytes)
        
        return {
            "message": "Export processed successfully",
            "stats": stats
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

