
import json
import requests
from flask import Flask, render_template_string

# ─────────────────────────────────────────
# 1) Kiwoom REST API 설정
# ─────────────────────────────────────────
HOST = "https://api.kiwoom.com"
API_ENDPOINT = "/api/dostk/stkinfo"  # ka10015
API_ID = "ka10015"

#ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
ACCESS_TOKEN = "cftvlTjo5uDsmEnQn8aiNfTewJj__W35Djz4jx1GgdwHUuNdHIUEIz1f8lkg7xLuMpLhX"


def load_json_file(filename="ncsrreq_pretty.json"):
    """파일에서 종목 리스트 로드"""
    with open(filename, "r", encoding="utf-8") as f:
        return json.load(f)


def request_trade_value(stock_code):
    """키움 REST API ka10015 이용한 거래대금 조회"""

    # 종목코드 "A000660" → "000660"
    code = stock_code.replace("A", "")

    url = HOST + API_ENDPOINT

    headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "authorization": f"Bearer {ACCESS_TOKEN}",
        "api-id": API_ID,
        "cont-yn": "N",
        "next-key": "",
    }

    # 요청 데이터
    body = {
        "stk_cd": code,
        "strt_dt": "20251208",  # 조회시작일(원하면 오늘 기준으로 수정가능)
    }

    response = requests.post(url, headers=headers, json=body)

    try:
        data = response.json()
    except:
        return None

    return data


# ─────────────────────────────────────────
# 2) Flask 웹 서버 구성
# ─────────────────────────────────────────
app = Flask(__name__)

HTML_PAGE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>종목별 거래대금 조회</title>

    <style>
        body { font-family: Arial; padding: 20px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 8px; border: 1px solid #ccc; text-align: center; }
        th { background: #333; color: white; }
        tr:nth-child(even) { background: #f4f4f4; }
        .money { font-weight: bold; color: #1a73e8; }
    </style>
</head>
<body>

<h2>📊 종목별 거래대금 (Kiwoom REST API ka10015)</h2>

<table>
    <tr>
        <th>종목코드</th>
        <th>종목명</th>
        <th>날짜</th>
        <th>종가</th>
        <th>거래량</th>
        <th>거래대금</th>
    </tr>

    {% for row in results %}
    <tr>
        <td>{{ row.code }}</td>
        <td>{{ row.name }}</td>
        <td>{{ row.date }}</td>
        <td>{{ "{:,}".format(row.price) }}</td>
        <td>{{ "{:,}".format(row.volume) }}</td>
        <td class="money">{{ "{:,}".format(row.value) }}</td>
    </tr>
    {% endfor %}
</table>

</body>
</html>
"""


@app.route("/")
def index():
    raw = load_json_file()

    results = []

    for item in raw:
        code = item["9001"]
        name = item["302"]

        # API 요청
        data = request_trade_value(code)
        if not data or data.get("return_code") != 0:
            continue

        # 응답 본문
        body = data["data"][0]

        date = body["bstp_n"]                # 일자
        price = int(body["stck_clpr"])       # 종가
        volume = int(body["acml_vol"])       # 거래량
        trade_value = int(body["acml_tr_pbmn"])  # 거래대금

        results.append({
            "code": code,
            "name": name,
            "date": date,
            "price": price,
            "volume": volume,
            "value": trade_value,
        })

    # 거래대금 순으로 정렬
    results.sort(key=lambda x: x["value"], reverse=True)

    return render_template_string(HTML_PAGE, results=results)


# ─────────────────────────────────────────
# 3) 실행
# ─────────────────────────────────────────
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
