"""Excel parsing routes for Revenue Cockpit bootstrap."""
from __future__ import annotations

import os
from pathlib import Path
from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from app.excel_service import parse_revenue_sheet

router = APIRouter(prefix="/excel", tags=["excel"])

NAS_ROOT = Path(os.getenv("NAS_ROOT", "/nas"))

DEFAULT_FILE = os.getenv("CEO_EXCEL_PATH", "Succes Sheet .xlsx")
DEFAULT_SHEET = os.getenv("CEO_EXCEL_SHEET", "Projects next steps revenue")


class RevenueParseBody(BaseModel):
    path: str = Field(default=DEFAULT_FILE)
    sheet: Optional[str] = Field(default=DEFAULT_SHEET)


@router.get("/revenue-sheet/preview")
def preview_revenue_sheet(path: str = DEFAULT_FILE, sheet: Optional[str] = DEFAULT_SHEET) -> dict:
    if not NAS_ROOT.is_dir():
        raise HTTPException(503, f"NAS not mounted at {NAS_ROOT}")
    result = parse_revenue_sheet(NAS_ROOT, path, sheet)
    if not result.get("ok"):
        raise HTTPException(400, result.get("error") or "Parse failed")
    return result


@router.post("/revenue-sheet/parse")
def parse_revenue_sheet_api(body: RevenueParseBody) -> dict:
    if not NAS_ROOT.is_dir():
        raise HTTPException(503, f"NAS not mounted at {NAS_ROOT}")
    result = parse_revenue_sheet(NAS_ROOT, body.path, body.sheet)
    if not result.get("ok"):
        raise HTTPException(400, result.get("error") or "Parse failed")
    return result
