import sys
import os
import random
import time
from datetime import datetime

def clear_screen():
    print("\033[H\033[J", end="")

def update_display(seed, num_tickets, num_simulations, current_sim, rank_list, combination_result):
    clear_screen()
    print(f"입력 시드: {seed}")
    print(f"구매 티켓 수: {num_tickets}")
    print(f"시뮬레이션 횟수: {num_simulations}")
    print(f"시뮬레이션 진행 중 {current_sim}/{num_simulations}...")
    print(f"현재 생성된 조합목록: {combination_result}")
    print("\n" + "-" * 30)
    print(f"1등: {rank_list[0]:5d} | 2등: {rank_list[1]:5d}")
    print(f"3등: {rank_list[2]:5d} | 4등: {rank_list[3]:5d}")
    print(f"낙첨: {rank_list[4]:5d}")
    print(f"시도횟수: {sum(rank_list):5d}")
    print("-" * 30)

def generate_lotto_numbers(seed):
    random.seed(seed)
    return sorted(random.sample(range(1, 46), 6))

def compare_numbers(winning_numbers, my_numbers):
    matches = len(set(winning_numbers) & set(my_numbers))
    if matches == 6:
        return 0
    elif matches == 5:
        return 1
    elif matches == 4:
        return 2
    elif matches == 3:
        return 3
    else:
        return 4

def generate_complex_seed(seed):
    current_time = int(time.time() * 1000000)
    mixed_bits = ((current_time & 0xff000000) >> 24) + \
                 ((current_time & 0x00ff0000) >> 8) + \
                 ((current_time & 0x0000ff00) << 8) + \
                 ((current_time & 0x000000ff) << 24)
    extra_random = random.randint(0, seed)
    final_seed = mixed_bits ^ extra_random
    return final_seed

def main(seed, num_tickets, num_simulations):
    rank_result = []
    combination_result = []
    for i in range(num_simulations):
        flag = True
        itr = 0
        rank_list = [0,0,0,0,0]
        while flag :
            seed = generate_complex_seed(seed)
            goal = generate_lotto_numbers(seed)

            for j in range(num_tickets):
                seed = generate_complex_seed(seed)
                combination = generate_lotto_numbers(seed)
                rank = compare_numbers(goal, combination)
                rank_list[rank] += 1
                itr += 1

                if rank == 0 :
                    flag = False

                if itr % 191 == 0:
                    update_display(seed, num_tickets, num_simulations, i+1, rank_list, combination_result)

        rank_result.append(rank_list)
        combination_result.append(goal)

    now = datetime.now()
    filename = now.strftime('result_%y%m%d_%H%M%S.txt')

    with open(filename, 'w') as f:
        for i, (rank, combination) in enumerate(zip(rank_result, combination_result), 1):
            total_attempts = sum(rank)
            f.write(f"{i}회째 결과 총 {total_attempts}번 시도\n")
            f.write(f"1등 : {rank[0]} 2등 : {rank[1]} 3등 : {rank[2]} 4등 : {rank[3]} 낙첨 : {rank[4]}\n\n")

        f.write("최종 조합\n")
        for combination in combination_result:
            f.write(' '.join(map(str, combination)) + '\n')

    print(f"결과가 '{filename}' 파일에 저장되었습니다.")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("사용법: python script.py <시드> <구매_티켓_수> <시뮬레이션_횟수>")
        sys.exit(1)

    seed = int(sys.argv[1])
    num_tickets = int(sys.argv[2])
    num_simulations = int(sys.argv[3])

    main(seed, num_tickets, num_simulations)