import asyncio
import sqlite3
import os
import sys
from pathlib import Path

sys.path.insert(0, r'D:\Workspace\claudeCode\AutonetSellCar.com\backend')
os.chdir(r'D:\Workspace\claudeCode\AutonetSellCar.com\backend')

from app.services.pdf_service import capture_performance_check_pdf

async def fix_missing_pdfs():
    conn = sqlite3.connect('autonet.db')
    cursor = conn.cursor()

    # Find cars with check_number but no pdf_path
    cursor.execute("""
        SELECT car_id, check_number, pdf_path
        FROM car_performance_checks
        WHERE check_number IS NOT NULL AND check_number != ''
        AND (pdf_path IS NULL OR pdf_path = '')
    """)

    missing = cursor.fetchall()
    print(f"PDF 없는 성능점검 레코드: {len(missing)}개")

    for car_id, check_num, pdf_path in missing:
        print(f"\n차량 {car_id}: check_num={check_num}")
        print(f"  PDF 생성 중...")

        try:
            pdf = await capture_performance_check_pdf(check_num, car_id)
            if pdf:
                cursor.execute(
                    "UPDATE car_performance_checks SET pdf_path = ? WHERE car_id = ?",
                    (pdf, car_id)
                )
                conn.commit()
                print(f"  [OK] PDF: {pdf}")
            else:
                print(f"  [FAIL] PDF generation failed")
        except Exception as e:
            print(f"  [ERROR] {e}")

    conn.close()
    print("\n완료!")

asyncio.run(fix_missing_pdfs())
