"""
ねんきんポータル API ルーター
"""
from fastapi import APIRouter, UploadFile, File, HTTPException
from app.core.database import get_connection
from app.modules.nenkin_portal.service import parse_zip

router = APIRouter(prefix="/nenkin", tags=["ねんきんポータル"])


# ──────────────────────────────────────
# POST /nenkin/upload
# ──────────────────────────────────────

@router.post("/upload", summary="社会保険電子文書 ZIPアップロード")
async def upload_nenkin_zip(file: UploadFile = File(...)):
    if not file.filename.lower().endswith('.zip'):
        raise HTTPException(status_code=400, detail="ZIPファイルを選択してください")

    data = await file.read()

    try:
        parsed = parse_zip(data, file.filename)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"ZIPの解析に失敗しました: {e}")

    doc_no = parsed['document_no']
    if not doc_no:
        raise HTTPException(status_code=400, detail="文書番号が取得できませんでした")

    with get_connection() as conn, conn.cursor() as cur:
        # 重複チェック
        cur.execute(
            "SELECT id FROM nenkin_documents WHERE document_no = %s",
            (doc_no,)
        )
        if cur.fetchone():
            raise HTTPException(
                status_code=409,
                detail=f"文書番号 {doc_no} は既に登録されています"
            )

        # nenkin_documents に挿入
        cur.execute("""
            INSERT INTO nenkin_documents
                (document_no, document_type, document_type_name, zip_filename,
                 office_name, office_number, office_kigo, nenkin_jimusho,
                 purpose_year, purpose_month, issue_date)
            VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
            RETURNING id
        """, (
            parsed['document_no'],
            parsed['document_type'],
            parsed['document_type_name'],
            parsed['zip_filename'],
            parsed['office_name'],
            parsed['office_number'],
            parsed['office_kigo'],
            parsed['nenkin_jimusho'],
            parsed['purpose_year'],
            parsed['purpose_month'],
            parsed['issue_date'],
        ))
        doc_id = cur.fetchone()['id']

        detail = parsed['detail']

        if parsed['document_type'] == 'SHAKAI':
            cur.execute("""
                INSERT INTO nenkin_shakai_hokenryo
                    (document_id, kenkou_hokenryo, kousei_nenkin_hokenryo,
                     kodomo_kyoshutsukin, total, nofu_kigen_date,
                     office_postcode, office_address)
                VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
            """, (
                doc_id,
                detail['kenkou_hokenryo'],
                detail['kousei_nenkin_hokenryo'],
                detail['kodomo_kyoshutsukin'],
                detail['total'],
                detail['nofu_kigen_date'],
                detail['office_postcode'],
                detail['office_address'],
            ))

        elif parsed['document_type'] == 'NOUNYU':
            cur.execute("""
                INSERT INTO nenkin_nounyu_tsuchi
                    (document_id,
                     kokuchi_kenkou, kokuchi_kounen, kokuchi_kodomo, kokuchi_total, kokuchi_nofu_kigen,
                     ryoshu_kenkou, ryoshu_kounen, ryoshu_kodomo, ryoshu_total, ryoshu_date,
                     ryoshu_nofu_year, ryoshu_nofu_month,
                     office_postcode, office_address, office_name_line1, office_name_line2)
                VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
            """, (
                doc_id,
                detail['kokuchi_kenkou'], detail['kokuchi_kounen'],
                detail['kokuchi_kodomo'], detail['kokuchi_total'],
                detail['kokuchi_nofu_kigen'],
                detail['ryoshu_kenkou'], detail['ryoshu_kounen'],
                detail['ryoshu_kodomo'], detail['ryoshu_total'],
                detail['ryoshu_date'],
                detail['ryoshu_nofu_year'], detail['ryoshu_nofu_month'],
                detail['office_postcode'], detail['office_address'],
                detail['office_name_line1'], detail['office_name_line2'],
            ))

        elif parsed['document_type'] == 'SHOYO':
            cur.execute("""
                INSERT INTO nenkin_shoyo_header
                    (document_id, jin_in_num, menjyo_hokenryo_ritsu, page_num)
                VALUES (%s,%s,%s,%s)
                RETURNING id
            """, (
                doc_id,
                detail['jin_in_num'],
                detail['menjyo_hokenryo_ritsu'],
                detail['page_num'],
            ))
            header_id = cur.fetchone()['id']

            for item in detail['items']:
                cur.execute("""
                    INSERT INTO nenkin_shoyo_detail
                        (document_id, header_id, seiri_num, shimei, shori_ymd, hassei_ymd,
                         hyojun_shoyo_kenpo, hyojun_shoyo_kounen,
                         kenpo_hongetsu, kenpo_zengetsu,
                         kounen_hongetsu, kounen_zengetsu, page_num)
                    VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
                """, (
                    doc_id, header_id,
                    item['seiri_num'], item['shimei'],
                    item['shori_ymd'], item['hassei_ymd'],
                    item['hyojun_shoyo_kenpo'], item['hyojun_shoyo_kounen'],
                    item['kenpo_hongetsu'], item['kenpo_zengetsu'],
                    item['kounen_hongetsu'], item['kounen_zengetsu'],
                    item['page_num'],
                ))

        conn.commit()

    return {
        'id':                doc_id,
        'document_no':       parsed['document_no'],
        'document_type':     parsed['document_type'],
        'document_type_name': parsed['document_type_name'],
        'message':           f"{parsed['document_type_name']} を登録しました",
    }


# ──────────────────────────────────────
# GET /nenkin/documents
# ──────────────────────────────────────

@router.get("/documents", summary="文書一覧取得")
def list_documents(doc_type: str = None, year: int = None, month: int = None):
    conditions = []
    params = []

    if doc_type:
        conditions.append("document_type = %s")
        params.append(doc_type)
    if year:
        conditions.append("purpose_year = %s")
        params.append(year)
    if month:
        conditions.append("purpose_month = %s")
        params.append(month)

    where = ("WHERE " + " AND ".join(conditions)) if conditions else ""

    with get_connection() as conn, conn.cursor() as cur:
        cur.execute(f"""
            SELECT id, document_no, document_type, document_type_name,
                   zip_filename, office_name, office_number, office_kigo,
                   nenkin_jimusho, purpose_year, purpose_month,
                   issue_date, uploaded_at
            FROM nenkin_documents
            {where}
            ORDER BY purpose_year DESC, purpose_month DESC, document_type, uploaded_at DESC
        """, params)
        rows = cur.fetchall()

    result = []
    for r in rows:
        item = dict(r)
        if item.get('issue_date'):
            item['issue_date'] = item['issue_date'].isoformat()
        if item.get('uploaded_at'):
            item['uploaded_at'] = item['uploaded_at'].isoformat()
        result.append(item)
    return result


# ──────────────────────────────────────
# GET /nenkin/documents/{doc_id}
# ──────────────────────────────────────

@router.get("/documents/{doc_id}", summary="文書詳細取得")
def get_document(doc_id: int):
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("SELECT * FROM nenkin_documents WHERE id = %s", (doc_id,))
        doc = cur.fetchone()
        if not doc:
            raise HTTPException(status_code=404, detail="文書が見つかりません")

        doc = dict(doc)
        if doc.get('issue_date'):
            doc['issue_date'] = doc['issue_date'].isoformat()
        if doc.get('uploaded_at'):
            doc['uploaded_at'] = doc['uploaded_at'].isoformat()

        detail = {}
        dtype = doc['document_type']

        if dtype == 'SHAKAI':
            cur.execute(
                "SELECT * FROM nenkin_shakai_hokenryo WHERE document_id = %s",
                (doc_id,)
            )
            row = cur.fetchone()
            if row:
                detail = dict(row)
                if detail.get('nofu_kigen_date'):
                    detail['nofu_kigen_date'] = detail['nofu_kigen_date'].isoformat()

        elif dtype == 'NOUNYU':
            cur.execute(
                "SELECT * FROM nenkin_nounyu_tsuchi WHERE document_id = %s",
                (doc_id,)
            )
            row = cur.fetchone()
            if row:
                detail = dict(row)
                for df in ('kokuchi_nofu_kigen', 'ryoshu_date'):
                    if detail.get(df):
                        detail[df] = detail[df].isoformat()

        elif dtype == 'SHOYO':
            cur.execute(
                "SELECT * FROM nenkin_shoyo_header WHERE document_id = %s",
                (doc_id,)
            )
            hdr = cur.fetchone()
            if hdr:
                detail = dict(hdr)
                cur.execute("""
                    SELECT * FROM nenkin_shoyo_detail
                    WHERE document_id = %s
                    ORDER BY CAST(NULLIF(TRIM(seiri_num), '') AS INTEGER) NULLS LAST
                """, (doc_id,))
                detail['items'] = [dict(r) for r in cur.fetchall()]

    return {'document': doc, 'detail': detail}


# ──────────────────────────────────────
# GET /nenkin/filter-options
# ──────────────────────────────────────

@router.get("/filter-options", summary="フィルター選択肢取得")
def get_filter_options():
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            SELECT DISTINCT purpose_year, purpose_month
            FROM nenkin_documents
            WHERE purpose_year IS NOT NULL
            ORDER BY purpose_year DESC, purpose_month DESC
        """)
        periods = [dict(r) for r in cur.fetchall()]

        cur.execute("""
            SELECT DISTINCT document_type, document_type_name
            FROM nenkin_documents
            ORDER BY document_type
        """)
        types = [dict(r) for r in cur.fetchall()]

    return {'periods': periods, 'types': types}
