"""성능점검표 가져오기 스크립트"""
import asyncio
import sys
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, '.')

from app.api.carmodoo import carmodoo_client
from app.database import SessionLocal
from app.models import Car, CarPerformanceCheck

async def fetch_and_save():
    db = SessionLocal()

    try:
        # 1. 최근 차량 중 성능점검표 없는 것 확인
        cars = db.query(Car).order_by(Car.id.desc()).limit(5).all()
        print("Recent cars:")
        for c in cars:
            perf = db.query(CarPerformanceCheck).filter(CarPerformanceCheck.car_id == c.id).first()
            print(f"  ID {c.id}: {c.source_id} - has_perf: {perf is not None}")

        # K5 차량 (ID 6) 처리
        car = db.query(Car).filter(Car.id == 6).first()
        if not car:
            print("Car ID 4 not found")
            return

        print(f"Car: {car.car_name}, source_id: {car.source_id}")

        # 2. 기존 성능점검표 삭제
        existing = db.query(CarPerformanceCheck).filter(CarPerformanceCheck.car_id == 4).first()
        if existing:
            db.delete(existing)
            db.commit()
            print("Deleted existing performance check")

        # 3. 카모두에서 성능점검표 가져오기
        print(f"Fetching performance check for car_no: {car.source_id}")
        result = await carmodoo_client.get_performance_check(car.source_id)

        print(f"Result found: {result.get('found')}")
        print(f"Check number: {result.get('check_num')}")

        if result.get('found') and result.get('data'):
            perf_data = result['data']
            print(f"Performance check data keys: {perf_data.keys()}")

            # 4. DB에 저장
            performance_check = CarPerformanceCheck(
                car_id=car.id,
                check_number=perf_data.get("check_number"),
                check_date=perf_data.get("check_date"),
                valid_until=perf_data.get("valid_until"),
                car_number=perf_data.get("car_number"),
                first_registration=perf_data.get("first_registration"),
                mileage=perf_data.get("mileage"),
                mileage_status=perf_data.get("mileage_status"),
                seize_count=perf_data.get("seize_count", 0),
                collateral_count=perf_data.get("collateral_count", 0),
                is_flood_damaged=perf_data.get("is_flood_damaged", False),
                is_fire_damaged=perf_data.get("is_fire_damaged", False),
                is_total_loss=perf_data.get("is_total_loss", False),
                usage_history=perf_data.get("usage_history"),
                is_rental_used=perf_data.get("is_rental_used", False),
                engine_status=perf_data.get("engine_status"),
                transmission_status=perf_data.get("transmission_status"),
                power_delivery_status=perf_data.get("power_delivery_status"),
                steering_status=perf_data.get("steering_status"),
                brake_status=perf_data.get("brake_status"),
                electrical_status=perf_data.get("electrical_status"),
                fuel_system_status=perf_data.get("fuel_system_status"),
                raw_data=perf_data,
                raw_html=result.get("raw_html", ""),
            )
            db.add(performance_check)
            db.commit()
            print(f"Saved performance check: {perf_data.get('check_number')}")
        else:
            print("No performance check data found from Carmodoo")
            print(f"Full result: {result}")

    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()

if __name__ == "__main__":
    asyncio.run(fetch_and_save())
