"""
IFRS + Dimensional Reports API Endpoints

Exposes combined IFRS and dimensional analysis reports through REST API.
"""

from typing import Optional, List
from datetime import date
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.user import User
from app.services.ifrs_dimensional_reports import IFRSDimensionalReports

router = APIRouter(prefix="/api/v1/reports/ifrs-dimensional", tags=["ifrs-dimensional-reports"])


@router.get("/combined-gl", response_model=dict)
def get_combined_gl(
    start_date: date = Query(..., description="Report start date (YYYY-MM-DD)"),
    end_date: date = Query(..., description="Report end date (YYYY-MM-DD)"),
    ifrs_tags: Optional[List[str]] = Query(None, description="Filter by IFRS tags (e.g., A1.1, L1.1)"),
    dimension_ids: Optional[List[str]] = Query(None, description="Filter by dimension IDs"),
    branch_id: Optional[str] = Query(None, description="Filter by branch ID"),
    group_by_ifrs: bool = Query(True, description="Group by IFRS category"),
    group_by_dimension: bool = Query(True, description="Group by dimension"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    Get General Ledger with IFRS tags and dimensional breakdowns combined.

    Returns journal entries grouped by IFRS category and dimension value,
    showing complete classification and allocation tracking.

    Example:
    GET /api/v1/reports/ifrs-dimensional/combined-gl?start_date=2025-01-01&end_date=2025-12-31&group_by_ifrs=true&group_by_dimension=true
    """
    try:
        service = IFRSDimensionalReports(db)
        result = service.get_combined_gl_with_dimensions(
            start_date=start_date,
            end_date=end_date,
            ifrs_tags=ifrs_tags,
            dimension_ids=dimension_ids,
            branch_id=branch_id,
            group_by_ifrs=group_by_ifrs,
            group_by_dimension=group_by_dimension
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/dimension/{dimension_id}/with-ifrs", response_model=dict)
def get_dimension_with_ifrs(
    dimension_id: str = Query(..., description="Dimension ID"),
    start_date: date = Query(..., description="Report start date"),
    end_date: date = Query(..., description="Report end date"),
    branch_id: Optional[str] = Query(None, description="Filter by branch ID"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    Show how a single dimension distributes across IFRS categories.

    For example: How does the Sales Department split between Assets, Liabilities, Revenue, and Expenses?

    Example:
    GET /api/v1/reports/ifrs-dimensional/dimension/{dept_id}/with-ifrs?start_date=2025-01-01&end_date=2025-12-31
    """
    try:
        service = IFRSDimensionalReports(db)
        result = service.get_dimension_with_ifrs_analysis(
            dimension_id=dimension_id,
            start_date=start_date,
            end_date=end_date,
            branch_id=branch_id
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/ifrs/{ifrs_tag}/with-dimensions", response_model=dict)
def get_ifrs_with_dimensions(
    ifrs_tag: str = Query(..., description="IFRS tag (e.g., A1.1, L1.1, R1)"),
    start_date: date = Query(..., description="Report start date"),
    end_date: date = Query(..., description="Report end date"),
    branch_id: Optional[str] = Query(None, description="Filter by branch ID"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    Show how a single IFRS category distributes across all dimensions.

    For example: How do Current Assets split across departments, projects, and cost centers?

    Example:
    GET /api/v1/reports/ifrs-dimensional/ifrs/A1.1/with-dimensions?start_date=2025-01-01&end_date=2025-12-31
    """
    try:
        service = IFRSDimensionalReports(db)
        result = service.get_ifrs_category_with_dimensions(
            ifrs_tag=ifrs_tag,
            start_date=start_date,
            end_date=end_date,
            branch_id=branch_id
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/coverage/validate", response_model=dict)
def validate_ifrs_dimension_coverage(
    start_date: date = Query(..., description="Report start date"),
    end_date: date = Query(..., description="Report end date"),
    branch_id: Optional[str] = Query(None, description="Filter by branch ID"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    Validate that all posted entries carry both IFRS tags and dimension assignments.

    Returns coverage metrics:
    - Total entries posted in period
    - Entries with IFRS tags (%)
    - Entries with dimensional assignments (%)
    - Entries with BOTH (%)
    - Audit alerts for entries missing tags

    A score of 100% indicates complete IFRS+Dimensional compliance.

    Example:
    GET /api/v1/reports/ifrs-dimensional/coverage/validate?start_date=2025-01-01&end_date=2025-12-31
    """
    try:
        service = IFRSDimensionalReports(db)
        result = service.validate_ifrs_dimension_coverage(
            start_date=start_date,
            end_date=end_date,
            branch_id=branch_id
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
