from fastapi import APIRouter, HTTPException, Query
from decimal import Decimal
from typing import Dict, Any, List, Optional
from app.modules.trial_balance.service import fetch_trial_balance
from app.core.database import get_connection

router = APIRouter(prefix="/trial-balance", tags=["試算表"])

@router.get("/fiscal-years", summary="仕訳データから会計年度一覧取得（5月期）")
def get_fiscal_years():
    REIWA_OFFSET = 2018  # 令和元年 = 2019年

    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            SELECT
                MIN(entry_date)::date AS min_date,
                MAX(entry_date)::date AS max_date
            FROM journal_entries
            WHERE is_deleted = false
        """)
        row = cur.fetchone()

    if not row or not row["min_date"]:
        return []

    min_date = row["min_date"]
    max_date = row["max_date"]

    def fiscal_end_year(d):
        return d.year + 1 if d.month >= 6 else d.year

    start_fy = fiscal_end_year(min_date)
    end_fy   = fiscal_end_year(max_date)

    result = []
    for fy in range(start_fy, end_fy + 1):
        reiwa = fy - REIWA_OFFSET
        if reiwa > 0:
            wareki = f"令和{reiwa}年"
        elif reiwa == 0:
            wareki = "平成31/令和元年"
        else:
            wareki = f"平成{fy - 1988}年"
        label = f"{wareki}({fy}年)5月期"
        result.append({
            "label":     label,
            "date_from": f"{fy - 1}-06-01",
            "date_to":   f"{fy}-05-31",
        })

    return result

@router.get("", summary="試算表（全科目）")
def get_trial_balance(
    fiscal_year: Optional[int] = Query(None, description="会計年度（例: 2025）"),
    date_from: Optional[str] = Query(None, description="YYYY-MM-DD"),
    date_to: Optional[str] = Query(None, description="YYYY-MM-DD"),
):
    # 👉 没传参数时，给默认值（开发期非常推荐）
    if fiscal_year is None:
        fiscal_year = 2025
    if date_from is None:
        date_from = "2025-01-01"
    if date_to is None:
        date_to = "2025-12-31"

    if date_from > date_to:
        raise HTTPException(status_code=400, detail="期間指定が不正です。")

    result = fetch_trial_balance(date_from, date_to)
    return result
