"""
기존 차량의 성능점검표를 가져오는 스크립트
"""
import asyncio
import sys
sys.path.insert(0, '.')

from sqlalchemy.orm import Session
from app.database import SessionLocal, engine
from app.models import Car, CarPerformanceCheck
from app.api.carmodoo import carmodoo_client


async def fetch_and_save_performance_check(car_id: int, car_no: str):
    """특정 차량의 성능점검표를 가져와서 저장"""
    db = SessionLocal()

    try:
        # 이미 있는지 확인
        existing = db.query(CarPerformanceCheck).filter(
            CarPerformanceCheck.car_id == car_id
        ).first()

        if existing:
            print(f"Car {car_id} already has performance check")
            return False

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

        # raw_html 저장 (디버깅용)
        if result.get("raw_html"):
            with open(f"./debug_perf_check_{car_no}.html", "w", encoding="utf-8") as f:
                f.write(result["raw_html"])
            print(f"  Raw HTML saved to debug_perf_check_{car_no}.html (length: {len(result['raw_html'])})")

        if not result.get("found"):
            print(f"Performance check not found for car_no: {car_no}")
            return False

        perf_data = result["data"]
        print(f"Performance check found: {perf_data.get('check_number', 'N/A')}")

        # CarPerformanceCheck 생성
        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", "")[:50000],
            report_image_url=perf_data.get("report_image_url"),
        )
        db.add(performance_check)
        db.commit()

        print(f"Performance check saved for car {car_id}")
        return True

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


async def main():
    # 모든 차량 조회
    db = SessionLocal()
    cars = db.query(Car).filter(
        Car.source == "carmodoo",
        Car.source_id.isnot(None)
    ).all()
    db.close()

    print(f"Found {len(cars)} cars from carmodoo")

    for car in cars:
        print(f"\n--- Processing Car ID: {car.id}, Source ID: {car.source_id} ---")
        await fetch_and_save_performance_check(car.id, car.source_id)
        await asyncio.sleep(1)  # 서버 부하 방지


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