#!/usr/bin/env python3
"""Extract detail page info from AutoScout24 listing pages"""
import sys, re, json

html = sys.stdin.read()
nextdata = re.search(r'<script id="__NEXT_DATA__"[^>]*>(.*?)</script>', html, re.DOTALL)
if not nextdata:
    print(json.dumps({"error": "no next data"}))
    sys.exit(0)

data = json.loads(nextdata.group(1))
detail = data.get("props", {}).get("pageProps", {}).get("listingDetails", {})
veh = detail.get("vehicle", {})
price = detail.get("price", {})
loc = detail.get("location", {})
tech = detail.get("technicalFeatures", {})
hist = detail.get("vehicleHistory", {})
deal = detail.get("customer", {})

result = {
    "make": veh.get("make", "?"),
    "model": veh.get("model", "?"),
    "price": price.get("consumerPriceGross", "?"),
    "mileage": veh.get("mileage", "?"),
    "ez": veh.get("firstRegistrationDate", "?"),
    "power_kw": tech.get("power", "?"),
    "fuel": tech.get("fuelType", "?"),
    "city": loc.get("city", "?"),
    "zip": loc.get("zip", "?"),
    "transmission": tech.get("transmission", "?"),
    "doors": tech.get("doors", "?"),
    "color": tech.get("color", "?"),
    "dealer": deal.get("name", "?"),
    "is_private": deal.get("isPrivate", False),
    "description": (detail.get("description", "") or "")[:200],
    "damage": hist.get("damage", False),
    "accident_free": hist.get("accidentFree", None),
}

print(json.dumps(result, ensure_ascii=False))
