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


def date_to_str(today):

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


def str_to_date(trading_day: str):
    year = int(trading_day[:4])
    month = int(trading_day[5:7])
    day = int(trading_day[-2:])
    return date(year, month, day)


def get_trading_days(dir):
    df = pd.read_csv(f"{dir}/data_file/korea_trading_days.csv", index_col=0)
    df['날짜'] = df['날짜'].apply(lambda day: str_to_date(day))
    return df


def get_day_price(code: str, start_date:str):
    """
    네이버 금융 일별 시세 최대 수집

    :param code: 종목 코드 (예: 005930)
    :param sleep: 페이지 간 대기 시간 (차단 방지)
    :param as_json: True면 JSON 반환
    """

    sleep: float = 0.5

    url = "https://finance.naver.com/item/sise_day.naver"
    headers = {"User-Agent": "Mozilla/5.0"}

    page = 1
    all_data = []
    last_date = None

    try:

        while True:
            params = {"code": code, "page": page}
            res = requests.get(url, params=params, headers=headers)
            res.encoding = "euc-kr"

            soup = BeautifulSoup(res.text, "html.parser")
            table = soup.find("table", class_="type2")

            if not table:
                break

            rows = table.find_all("tr")
            page_data = []

            for row in rows:
                cols = row.find_all("td")
                if len(cols) != 7:
                    continue

                date = cols[0].get_text(strip=True)
                date = date.replace(".", "")

                # 기존에 없는 데이터만 수집
                if date < start_date:
                    break
                # 더 이상 과거 데이터가 없을 때
                if date == last_date:
                    continue

                page_data.append({
                    "날짜": date,
                    # "close": int(cols[1].get_text(strip=True).replace(",", "")),
                    # "diff": cols[2].get_text(strip=True),
                    # "open": int(cols[3].get_text(strip=True).replace(",", "")),
                    # "high": int(cols[4].get_text(strip=True).replace(",", "")),
                    # "low": int(cols[5].get_text(strip=True).replace(",", "")),
                    # "volume": int(cols[6].get_text(strip=True).replace(",", ""))
                })

            if not page_data:
                break  # 더 이상 데이터 없음 → 종료

            last_date = page_data[-1]["날짜"]
            all_data.extend(page_data)

            # print(f"[INFO] page {page} 수집 완료 ({len(page_data)} rows)")
            page += 1
            time.sleep(sleep)

        df = pd.DataFrame(all_data)
        df = df.drop_duplicates(subset="날짜").sort_values("날짜")

        df['날짜'] = df['날짜'].apply(lambda x : datetime.strptime(x, "%Y%m%d"))
        df['날짜'] = df['날짜'].apply(lambda x : x.strftime("%Y-%m-%d"))
        df['날짜'] = df['날짜'].apply(lambda x: str_to_date(x))

    except:
        print("(EXCEPT)[get_day_price] 수집할 거래일이 없습니다.")
        return

    return df


def generate_trading_days(dir, day):

    try:
        os.makedirs(f"{dir}/data_file")
    except OSError:
        if not os.path.isdir(f"{dir}/data_file"):
            raise

    bef_trading_days = get_trading_days(dir)
    start_date = bef_trading_days['날짜'].iloc[-1]
    start_date = start_date + timedelta(days=1)

    end_date = day

    if start_date > end_date :

        print("수집할 거래일이 없습니다")

    else :

        str_start_date = date_to_str(start_date)
        str_end_date = date_to_str(end_date)

        try:

            str_start_date = date_to_str(start_date)

            new_trading_days = get_day_price("005930", str_start_date)

            df = pd.concat([bef_trading_days, new_trading_days])
            df = df.sort_values("날짜")
            df.index = np.arange(len(df))

            df.to_csv(f"{dir}/data_file/korea_trading_days.csv")

        except:

            print("(EXCEPT) 수집할 거래일이 없습니다.")


