import json
import requests
import pandas as pd
import numpy as np
from datetime import date, timedelta
from time import sleep
import os

def int_to_str(x: int) -> str:
    return "%06d" % x

def date_to_str(today):

    str_date = str(today)[:4] + str(today)[5:7] + str(today)[-2:]
    return str_date

def str_to_date(str_date):

    str_date = str_date.replace('-', '')
    year = int(str_date[:4])
    month = int(str_date[4:6])
    day = int(str_date[-2:])
    return date(year,month,day)

def get_trading_days(dir, start_date: date, end_date: date):

    df = pd.read_csv(f"{dir}/data_file/korea_trading_days.csv", index_col=0)
    df['날짜'] = df['날짜'].apply(lambda day: str_to_date(day))
    trading_days = df['날짜'].to_list()
    trading_days = [day for day in trading_days if start_date <= day <= end_date]
    return trading_days

def get_kosdaq_price(today:str, api):

    print(today)

    # 코스피 데이터 수집
    url = "https://data-dbg.krx.co.kr/svc/apis/idx/kosdaq_dd_trd"

    headers = {
        "AUTH_KEY": api,
        "Accept": "application/json"
    }

    params = {
        "basDd": today  # 조회할 날짜: YYYYMMDD
    }

    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()

    data = response.json()

    # OutBlock_1 추출
    records = data.get("OutBlock_1", [])

    # DataFrame 변환
    df = pd.DataFrame(records)
    df = df.replace(',', '', regex=True)
    df = df[df["IDX_NM"] == "코스닥"].reset_index(drop=True)

    df = df.drop(['IDX_CLSS', 'IDX_NM', 'CMPPREVDD_IDX', 'FLUC_RT'], axis='columns')

    df['BAS_DD'] = df['BAS_DD'].apply(lambda x : str_to_date(x))

    cols_map = {'BAS_DD':'날짜', 'CLSPRC_IDX':'종가', 'OPNPRC_IDX':'시가', 'HGPRC_IDX':'고가',
                'LWPRC_IDX':'저가', 'ACC_TRDVOL':'거래량', 'ACC_TRDVAL':'거래대금', 'MKTCAP':'시가총액'}

    df = df.rename(columns=cols_map)
    df = df[['날짜','종가','시가','고가','저가','거래량','거래대금','시가총액']]
    df = df.sort_values('날짜', ascending=True)

    return df


def generate_kosdaq_price(dir, today, api):

    end_date = today

    bef_kosdaq_price = pd.read_csv(f"{dir}/data_file/Kosdaq_Price.csv")
    bef_kosdaq_price['날짜'] = bef_kosdaq_price['날짜'].apply(lambda x : str_to_date(x))
    start_date = bef_kosdaq_price['날짜'].iloc[-1] + timedelta(days=1)

    if start_date > end_date:
        print("수집할 코스닥 INDEX가 없습니다")

    trading_days = get_trading_days(dir, start_date, end_date)

    if len(trading_days) == 0:
        print("수집할 코스닥 INDEX가 없습니다")

    else:
        trading_days = [date_to_str(day) for day in trading_days]
        aft_kosdaq_price = get_kosdaq_price(trading_days[0], api)

        for i, now_day in enumerate(trading_days):

            if i == 0:
                continue

            df2 = get_kosdaq_price(now_day, api)
            aft_kosdaq_price = pd.concat([aft_kosdaq_price, df2])
            sleep(1)

        try:
            kosdaq_price = pd.concat([bef_kosdaq_price, aft_kosdaq_price])
            kosdaq_price = kosdaq_price.reset_index()
        except:
            pass

        df = kosdaq_price[['날짜','종가','시가','고가','저가','거래량','거래대금','시가총액']]
        df.index = np.arange(len(df))

        df.to_csv(f"{dir}/data_file/Kosdaq_Price.csv")
        print("코스닥 INDEX 수집완료")
