import sys
sys.stdout.reconfigure(encoding='utf-8')

import time
import os
from pathlib import Path

SCRIPT_DIR = Path(__file__).parent
CAPTCHA_IMAGE = SCRIPT_DIR / 'captcha_to_read.png'
CAPTCHA_ANSWER = SCRIPT_DIR / 'captcha_answer.txt'

print("自動驗證碼辨識器啟動...")
print(f"監控圖片: {CAPTCHA_IMAGE}")
print(f"答案檔案: {CAPTCHA_ANSWER}")
print("=" * 60)

last_modified = 0
solved_count = 0

while True:
    try:
        # 檢查驗證碼圖片是否存在且有更新
        if os.path.exists(CAPTCHA_IMAGE):
            current_modified = os.path.getmtime(CAPTCHA_IMAGE)

            # 如果圖片有更新且答案檔不存在（代表需要辨識）
            if current_modified > last_modified and not os.path.exists(CAPTCHA_ANSWER):
                print(f"\n[{solved_count + 1}] 發現新驗證碼圖片！")
                print(f"  修改時間: {time.ctime(current_modified)}")
                print("  >>> 請 Claude 讀取圖片並辨識驗證碼 <<<")
                print(f"  圖片位置: {CAPTCHA_IMAGE}")
                print("  等待辨識中...")

                last_modified = current_modified
                solved_count += 1

                # 等待答案檔案出現（最多等 30 秒）
                waited = 0
                while not os.path.exists(CAPTCHA_ANSWER) and waited < 30:
                    time.sleep(0.5)
                    waited += 0.5

                if os.path.exists(CAPTCHA_ANSWER):
                    with open(CAPTCHA_ANSWER, 'r') as f:
                        answer = f.read().strip()
                    print(f"  ✓ 已辨識: {answer}")
                else:
                    print("  ⚠ 等待超時")

        time.sleep(1)

    except KeyboardInterrupt:
        print("\n停止監控")
        break
    except Exception as e:
        print(f"錯誤: {e}")
        time.sleep(1)
