from scraper import fetch_latest_lottery
from db import execute_query
from telegram_bot import send_telegram_message
from config import LOTTERY_RULES
from datetime import datetime

def slice_number(raw_num):
    if not raw_num or len(str(raw_num).strip()) < 5:
        return "N/A", "N/A"
    num_str = str(raw_num).strip()
    return num_str[LOTTERY_RULES['2d_slice']], num_str[LOTTERY_RULES['3d_slice']]

def process_and_broadcast_result(target_time=None):
    results = fetch_latest_lottery()
    if not results:
        print("⚠️ មិនទាន់មានទិន្នន័យពី Scraping ទេ")
        return

    # ស្វែងរកលទ្ធផលត្រូវតាមម៉ោង (ឬយកលទ្ធផលចុងក្រោយគេ)
    target_result = None
    if target_time:
        for res in results:
            if res['draw_time'] == target_time:
                target_result = res
                break
    else:
        target_result = results[0]

    if not target_result:
        print(f"⚠️ មិនទាន់ឃើញលទ្ធផលចេញសម្រាប់ម៉ោង {target_time} ទេ")
        return

    draw_time = target_result['draw_time']
    today_date = datetime.now().strftime('%Y-%m-%d')

    # ១. ពិនិត្យក្នុង DB ការពារការ Save និង បោះសារស្ទួន
    check_query = "SELECT id FROM lottery_results WHERE draw_date = %s AND draw_time = %s"
    existing = execute_query(check_query, (today_date, draw_time), fetch_one=True)

    if not existing:
        # ២. Auto Save ចូល Database
        insert_query = """
            INSERT INTO lottery_results (draw_date, draw_time, prize_a, prize_b, prize_c, prize_d)
            VALUES (%s, %s, %s, %s, %s, %s)
        """
        execute_query(
            insert_query, 
            (today_date, draw_time, target_result['prize_a'], target_result['prize_b'], target_result['prize_c'], target_result['prize_d']), 
            commit=True
        )
        print(f"💾 [DB Auto Saved] លទ្ធផលម៉ោង {draw_time} ត្រូវបានរក្សាទុកក្នុង DB!")

        # ៣. កាត់លេខ 2D/3D
        a_2d, a_3d = slice_number(target_result['prize_a'])
        b_2d, b_3d = slice_number(target_result['prize_b'])
        c_2d, c_3d = slice_number(target_result['prize_c'])
        d_2d, d_3d = slice_number(target_result['prize_d'])

        # ៤. រៀបចំសារ និងបោះចូល Telegram តាមម៉ោងចេញ
        msg = f"🔴 *លទ្ធផលឆ្នោតខ្មែរចេញពិតប្រាកដ* 🔴\n"
        msg += f"📅 ថ្ងៃទី: `{today_date}` | ⏰ ម៉ោង: `{draw_time}`\n"
        msg += f"----------------------------------\n"
        msg += f"🅰️ **រង្វាន់ A**: `{target_result['prize_a']}` ➔ (2D: `{a_2d}` | 3D: `{a_3d}`)\n"
        msg += f"བ **រង្វាន់ B**: `{target_result['prize_b']}` ➔ (2D: `{b_2d}` | 3D: `{b_3d}`)\n"
        msg += f"🇨 **រង្វាន់ C**: `{target_result['prize_c']}` ➔ (2D: `{c_2d}` | 3D: `{c_3d}`)\n"
        msg += f"🇩 **រង្វាន់ D**: `{target_result['prize_d']}` ➔ (2D: `{d_2d}` | 3D: `{d_3d}`)\n"
        msg += f"----------------------------------"

        send_telegram_message(msg)
        print(f"🚀 [Telegram Sent] បានបោះលទ្ធផលម៉ោង {draw_time} ចូល Telegram រួចរាល់!")
    else:
        print(f"ℹ️ លទ្ធផលម៉ោង {draw_time} មានក្នុង DB រួចហើយ មិនបោះសារស្ទួនទេ")