import json
from .db import (
    _conn, get_draw, update_recommendation_result
)

def _calc_rank(my_nums: list[int], win_nums: list[int], bonus: int) -> tuple[int, int, bool]:
    """
    (rank, correct_cnt, has_bonus) 반환
    rank: 1~5 (1등~5등), 0 (낙첨)
    """
    matched = set(my_nums) & set(win_nums)
    cnt = len(matched)
    has_bonus = bonus in my_nums
    
    if cnt == 6:
        return 1, cnt, has_bonus
    if cnt == 5 and has_bonus:
        return 2, cnt, has_bonus
    if cnt == 5:
        return 3, cnt, has_bonus
    if cnt == 4:
        return 4, cnt, has_bonus
    if cnt == 3:
        return 5, cnt, has_bonus
        
    return 0, cnt, has_bonus

def check_results_for_draw(drw_no: int) -> int:
    """
    특정 회차(drw_no) 결과가 나왔을 때,
    해당 회차를 타겟으로 했던(based_on_draw == drw_no - 1) 추천들을 채점한다.
    반환값: 채점한 개수
    """
    win_row = get_draw(drw_no)
    if not win_row:
        return 0
        
    win_nums = [
        win_row["n1"], win_row["n2"], win_row["n3"],
        win_row["n4"], win_row["n5"], win_row["n6"]
    ]
    bonus = win_row["bonus"]
    
    # based_on_draw가 (이번회차 - 1)인 것들 조회
    # 즉, 1000회차 추첨 결과로는, 999회차 데이터를 바탕으로 1000회차를 예측한 것들을 채점
    target_based_on = drw_no - 1
    
    with _conn() as conn:
        rows = conn.execute(
            """
            SELECT id, numbers 
            FROM recommendations 
            WHERE based_on_draw = ? AND checked = 0
            """,
            (target_based_on,)
        ).fetchall()
        
    count = 0
    for r in rows:
        my_nums = json.loads(r["numbers"])
        rank, correct, has_bonus = _calc_rank(my_nums, win_nums, bonus)
        
        update_recommendation_result(r["id"], rank, correct, has_bonus)
        count += 1

    # ── 구매 이력 체크 연동 ──────────────────────────────────────
    try:
        from .purchase_manager import check_purchases_for_draw as _check_purchases
        _check_purchases(drw_no)  # 내부에서 evolve_after_check → recalculate_weights 호출
    except ImportError:
        pass  # purchase_manager 미설치 시 무시 (하위호환)

    return count
