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

"""

import logging
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__)

##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 매수주문 [국내주식-124]
##############################################################################################

# 상수 정의
API_URL = "/uapi/domestic-bond/v1/trading/buy"

def buy(
        cano: str,
        acnt_prdt_cd: str,
        pdno: str,
        ord_qty2: str,
        bond_ord_unpr: str,
        samt_mket_ptci_yn: str,
        bond_rtl_mket_yn: str,
        idcr_stfno: str = "",
        mgco_aptm_odno: str = "",
        ord_svr_dvsn_cd: str = "",
        ctac_tlno: str = ""
) -> Optional[pd.DataFrame]:
    """
    [장내채권] 주문/계좌 
    장내채권 매수주문[국내주식-124]
    장내채권 매수주문 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        cano (str): 종합계좌번호 (8자리)
        acnt_prdt_cd (str): 계좌상품코드 (2자리)
        pdno (str): 상품번호 (12자리)
        ord_qty2 (str): 주문수량2 (19자리)
        bond_ord_unpr (str): 채권주문단가 (182자리)
        samt_mket_ptci_yn (str): 소액시장참여여부 ('Y' or 'N')
        bond_rtl_mket_yn (str): 채권소매시장여부 ('Y' or 'N')
        idcr_stfno (str, optional): 유치자직원번호 (6자리). Defaults to "".
        mgco_aptm_odno (str, optional): 운용사지정주문번호 (12자리). Defaults to "".
        ord_svr_dvsn_cd (str, optional): 주문서버구분코드. Defaults to "".
        ctac_tlno (str, optional): 연락전화번호. Defaults to "".
        
    Returns:
        Optional[pd.DataFrame]: 장내채권 매수주문 데이터
        
    Example:
        >>> df = buy(
        ...     cano=trenv.my_acct, 
        ...     acnt_prdt_cd=trenv.my_prod,
        ...     pdno="KR1234567890", 
        ...     ord_qty2="10", 
        ...     bond_ord_unpr="10000",
        ...     samt_mket_ptci_yn="N",
        ...     bond_rtl_mket_yn="Y"
        ... )
        >>> print(df)
    """
    tr_id = "TTTC0952U"

    params = {
        "CANO": cano,
        "ACNT_PRDT_CD": acnt_prdt_cd,
        "PDNO": pdno,
        "ORD_QTY2": ord_qty2,
        "BOND_ORD_UNPR": bond_ord_unpr,
        "SAMT_MKET_PTCI_YN": samt_mket_ptci_yn,
        "BOND_RTL_MKET_YN": bond_rtl_mket_yn,
        "IDCR_STFNO": idcr_stfno,
        "MGCO_APTM_ODNO": mgco_aptm_odno,
        "ORD_SVR_DVSN_CD": ord_svr_dvsn_cd,
        "CTAC_TLNO": ctac_tlno,
    }

    res = ka._url_fetch(api_url=API_URL,
                        ptr_id=tr_id,
                        tr_cont="",
                        params=params,
                        postFlag=True
                        )

    if res.isOK():
        if hasattr(res.getBody(), 'output'):
            output_data = res.getBody().output
            if not isinstance(output_data, list):
                output_data = [output_data]
            dataframe = pd.DataFrame(output_data)
        else:
            dataframe = pd.DataFrame()

        logger.info("Data fetch complete.")
        return dataframe
    else:
        logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
        res.printError(API_URL)
        return pd.DataFrame()
