# [장내채권] 주문/계좌 - 장내채권 주문체결내역
# Generated by KIS API Generator (Single API Mode)
# -*- coding: utf-8 -*-
"""
Created on 2025-06-20

"""

import logging
import time
from typing import Optional, Tuple
import sys

import pandas as pd

sys.path.extend(['../..', '.'])
import kis_auth as ka

# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 일별체결조회 [국내주식-127]
##############################################################################################

# 상수 정의
API_URL = "/uapi/domestic-bond/v1/trading/inquire-daily-ccld"

def inquire_daily_ccld(
        cano: str,  # 종합계좌번호
        acnt_prdt_cd: str,  # 계좌상품코드
        inqr_strt_dt: str,  # 조회시작일자
        inqr_end_dt: str,  # 조회종료일자
        sll_buy_dvsn_cd: str,  # 매도매수구분코드
        sort_sqn_dvsn: str,  # 정렬순서구분
        pdno: str,  # 상품번호
        nccs_yn: str,  # 미체결여부
        ctx_area_nk200: str,  # 연속조회키200
        ctx_area_fk200: str,  # 연속조회검색조건200
        dataframe1: Optional[pd.DataFrame] = None,  # 누적 데이터프레임 (output1)
        dataframe2: Optional[pd.DataFrame] = None,  # 누적 데이터프레임 (output2)
        tr_cont: str = "",
        depth: int = 0,
        max_depth: int = 10
) -> Tuple[pd.DataFrame, pd.DataFrame]:
    """
    [장내채권] 주문/계좌 
    장내채권 주문체결내역[국내주식-127]
    장내채권 주문체결내역 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        cano (str): 종합계좌번호
        acnt_prdt_cd (str): 계좌상품코드
        inqr_strt_dt (str): 조회시작일자 (1주일 이내)
        inqr_end_dt (str): 조회종료일자 (조회 당일)
        sll_buy_dvsn_cd (str): 매도매수구분코드 (%(전체), 01(매도), 02(매수))
        sort_sqn_dvsn (str): 정렬순서구분 (01(주문순서), 02(주문역순))
        pdno (str): 상품번호
        nccs_yn (str): 미체결여부 (N(전체), C(체결), Y(미체결))
        ctx_area_nk200 (str): 연속조회키200
        ctx_area_fk200 (str): 연속조회검색조건200
        dataframe1 (Optional[pd.DataFrame]): 누적 데이터프레임 (output1)
        dataframe2 (Optional[pd.DataFrame]): 누적 데이터프레임 (output2)
        tr_cont (str): 연속 거래 여부
        depth (int): 현재 재귀 깊이
        max_depth (int): 최대 재귀 깊이 (기본값: 10)
        
    Returns:
        Tuple[pd.DataFrame, pd.DataFrame]: 장내채권 주문체결내역 데이터
        
    Example:
        >>> df1, df2 = inquire_daily_ccld(
        ...     cano=trenv.my_acct,
        ...     acnt_prdt_cd=trenv.my_prod,
        ...     inqr_strt_dt='20230101',
        ...     inqr_end_dt='20230107',
        ...     sll_buy_dvsn_cd='01',
        ...     sort_sqn_dvsn='01',
        ...     pdno='000000000001',
        ...     nccs_yn='N',
        ...     ctx_area_nk200='',
        ...     ctx_area_fk200=''
        ... )
        >>> print(df1)
        >>> print(df2)
    """
    # 필수 파라미터 검증
    if not cano:
        logger.error("cano is required. (e.g. '12345678')")
        raise ValueError("cano is required. (e.g. '12345678')")
    if not acnt_prdt_cd:
        logger.error("acnt_prdt_cd is required. (e.g. '01')")
        raise ValueError("acnt_prdt_cd is required. (e.g. '01')")
    if not inqr_strt_dt:
        logger.error("inqr_strt_dt is required. (e.g. '20230101')")
        raise ValueError("inqr_strt_dt is required. (e.g. '20230101')")
    if not inqr_end_dt:
        logger.error("inqr_end_dt is required. (e.g. '20230107')")
        raise ValueError("inqr_end_dt is required. (e.g. '20230107')")
    if not sll_buy_dvsn_cd in ["%", "01", "02"]:
        logger.error("sll_buy_dvsn_cd is required. (e.g. '01')")
        raise ValueError("sll_buy_dvsn_cd is required. (e.g. '01')")
    if not sort_sqn_dvsn in ["01", "02"]:
        logger.error("sort_sqn_dvsn is required. (e.g. '01')")
        raise ValueError("sort_sqn_dvsn is required. (e.g. '01')")
    if not nccs_yn in ["N", "C", "Y"]:
        logger.error("nccs_yn is required. (e.g. 'N')")
        raise ValueError("nccs_yn is required. (e.g. 'N')")

    # 최대 재귀 깊이 체크
    if depth >= max_depth:
        logger.warning("Maximum recursion depth (%d) reached. Stopping further requests.", max_depth)
        return dataframe1 if dataframe1 is not None else pd.DataFrame(), dataframe2 if dataframe2 is not None else pd.DataFrame()

    tr_id = "CTSC8013R"

    params = {
        "CANO": cano,
        "ACNT_PRDT_CD": acnt_prdt_cd,
        "INQR_STRT_DT": inqr_strt_dt,
        "INQR_END_DT": inqr_end_dt,
        "SLL_BUY_DVSN_CD": sll_buy_dvsn_cd,
        "SORT_SQN_DVSN": sort_sqn_dvsn,
        "PDNO": pdno,
        "NCCS_YN": nccs_yn,
        "CTX_AREA_NK200": ctx_area_nk200,
        "CTX_AREA_FK200": ctx_area_fk200,
    }

    res = ka._url_fetch(API_URL, tr_id, tr_cont, params)

    if res.isOK():
        # output1 처리
        if hasattr(res.getBody(), 'output1'):
            output_data = res.getBody().output1
            if output_data:
                # output1은 단일 객체, output2는 배열일 수 있음
                if isinstance(output_data, list):
                    current_data1 = pd.DataFrame(output_data)
                else:
                    # 단일 객체인 경우 리스트로 감싸서 DataFrame 생성
                    current_data1 = pd.DataFrame([output_data])

                if dataframe1 is not None:
                    dataframe1 = pd.concat([dataframe1, current_data1], ignore_index=True)
                else:
                    dataframe1 = current_data1
            else:
                if dataframe1 is None:
                    dataframe1 = pd.DataFrame()
        else:
            if dataframe1 is None:
                dataframe1 = pd.DataFrame()
        # output2 처리
        if hasattr(res.getBody(), 'output2'):
            output_data = res.getBody().output2
            if output_data:
                # output1은 단일 객체, output2는 배열일 수 있음
                if isinstance(output_data, list):
                    current_data2 = pd.DataFrame(output_data)
                else:
                    # 단일 객체인 경우 리스트로 감싸서 DataFrame 생성
                    current_data2 = pd.DataFrame([output_data])

                if dataframe2 is not None:
                    dataframe2 = pd.concat([dataframe2, current_data2], ignore_index=True)
                else:
                    dataframe2 = current_data2
            else:
                if dataframe2 is None:
                    dataframe2 = pd.DataFrame()
        else:
            if dataframe2 is None:
                dataframe2 = pd.DataFrame()
        tr_cont = res.getHeader().tr_cont
        ctx_area_nk200 = res.getBody().ctx_area_nk200
        ctx_area_fk200 = res.getBody().ctx_area_fk200

        if tr_cont in ["M", "F"]:
            logger.info("Calling next page...")
            ka.smart_sleep()
            return inquire_daily_ccld(
                cano,
                acnt_prdt_cd,
                inqr_strt_dt,
                inqr_end_dt,
                sll_buy_dvsn_cd,
                sort_sqn_dvsn,
                pdno,
                nccs_yn,
                ctx_area_nk200,
                ctx_area_fk200,
                "N", dataframe1, dataframe2, depth + 1, max_depth
            )
        else:
            logger.info("Data fetch complete.")
            return dataframe1, dataframe2
    else:
        logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
        res.printError(API_URL)
        return pd.DataFrame(), pd.DataFrame()
