#!/usr/bin/env python3
"""오늘 모멘텀 거래종목 vs 유니버스 틱 커버 진단 (adhoc)."""
from __future__ import annotations

from database import TradeDB

DAY = "20260713"
CODES = ["475150", "039340", "241710"]
TRADE_MINS = [
    "202607130930",
    "202607130931",
    "202607130943",
    "202607130944",
    "202607130952",
    "202607130953",
    "202607130959",
    "202607131014",
    "202607131019",
    "202607131020",
    "202607131026",
    "202607131027",
    "202607131032",
    "202607131033",
    "202607131036",
    "202607131038",
    "202607131101",
    "202607131102",
    "202607131116",
    "202607131118",
]


def main() -> None:
    db = TradeDB()
    try:
        cols = [r["Field"] for r in db.conn.execute("SHOW COLUMNS FROM ws_ticks").fetchall()]
        print("ws_ticks sample cols:", cols[:12])

        for code in CODES:
            rows = db.conn.execute(
                "SELECT COUNT(*) n, MIN(tick_time) mn, MAX(tick_time) mx "
                "FROM ws_ticks WHERE code=%s AND tick_time LIKE %s",
                (code, DAY + "%"),
            ).fetchone()
            print(f"ticks {code}: n={rows['n']} range={rows['mn']}~{rows['mx']}")

        sk = db.conn.execute(
            "SELECT LEFT(tick_time,12) m, COUNT(*) n FROM ws_ticks "
            "WHERE code=%s AND tick_time >= %s AND tick_time <= %s "
            "GROUP BY LEFT(tick_time,12) ORDER BY m",
            ("475150", DAY + "090000", DAY + "113059"),
        ).fetchall()
        have = {r["m"]: int(r["n"]) for r in sk}
        print(f"SK minutes with ticks 09:00-11:30: {len(have)}")
        print("trade-related minutes tick count:")
        for m in TRADE_MINS:
            print(f"  {m[8:]} n={have.get(m, 0)}")

        nc = db.conn.execute(
            "SELECT COUNT(DISTINCT code) c FROM ws_ticks WHERE tick_time LIKE %s",
            (DAY + "%",),
        ).fetchone()
        print("distinct codes with ticks today:", nc["c"])

        try:
            cc = db.conn.execute(
                "SELECT COUNT(DISTINCT code) c FROM ws_candles "
                "WHERE candle_time LIKE %s AND timeframe=%s",
                (DAY + "%", 1),
            ).fetchone()
            print("distinct codes with 1m candles today:", cc["c"])
        except Exception as e:
            print("candles query skip:", e)

        # 30% coverage 의미: 유니버스 전종목 전분봉 중 틱 있는 분 비율
        # 거래 3종만 보면?
        for code in CODES:
            bars = db.conn.execute(
                "SELECT COUNT(DISTINCT LEFT(candle_time,12)) n FROM ws_candles "
                "WHERE code=%s AND candle_time LIKE %s AND timeframe=%s "
                "AND LEFT(candle_time,12) BETWEEN %s AND %s",
                (code, DAY + "%", 1, DAY + "0900", DAY + "1530"),
            ).fetchone()
            tmin = db.conn.execute(
                "SELECT COUNT(DISTINCT LEFT(tick_time,12)) n FROM ws_ticks "
                "WHERE code=%s AND tick_time LIKE %s "
                "AND LEFT(tick_time,12) BETWEEN %s AND %s",
                (code, DAY + "%", DAY + "0900", DAY + "1530"),
            ).fetchone()
            bn = int(bars["n"] or 0)
            tn = int(tmin["n"] or 0)
            pct = (100.0 * tn / bn) if bn else 0.0
            print(f"cover {code}: tick_mins={tn} candle_mins={bn} pct={pct:.1f}%")
    finally:
        db.close()


if __name__ == "__main__":
    main()
