"""
Build customer-ready spec-sheet PDFs from the raw build-sheet .txt dumps.

Standalone one-off:  py build_spec_sheets.py
Produces one PDF per car, named after the source .txt file.

Values are extracted straight from the source dumps (one comma-separated
feature line per car). Two minor inconsistencies in the 911 dump are resolved
to the internally-consistent figure:
    highway  10.2 & 10.1 L/100 km  -> 10.1  (consistent with city 13.8 / comb 12.1)
    combined 12.1 & 12.2 L/100 km  -> 12.1
    CO2      289 & 288 g/km        -> 288
Pure spec sheet — no dealer / price / contact block (per request).
"""
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.lib.colors import HexColor, white
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, KeepTogether,
)

# ---------------------------------------------------------------- palette ----
TEXT       = HexColor('#1a1a1a')
MUTED      = HexColor('#6b6b6b')
RULE       = HexColor('#dcdcdc')
ZEBRA      = HexColor('#f5f5f5')
SECTION_BG = HexColor('#1f1f1f')
ACCENT     = HexColor('#9a1b1b')   # subtle red rule under the title
CARD_BG    = HexColor('#f7f7f7')

# ---------------------------------------------------------------- styles -----
TITLE_ST  = ParagraphStyle('t', fontName='Helvetica-Bold', fontSize=20,
                           textColor=TEXT, leading=23, spaceAfter=2)
SUB_ST     = ParagraphStyle('s', fontName='Helvetica', fontSize=10,
                             textColor=MUTED, leading=13, spaceAfter=0)
SECT_ST    = ParagraphStyle('sec', fontName='Helvetica-Bold', fontSize=9.5,
                             textColor=white, leading=12)
LBL_ST     = ParagraphStyle('lbl', fontName='Helvetica', fontSize=8.5,
                            textColor=MUTED, leading=10.5)
VAL_ST     = ParagraphStyle('val', fontName='Helvetica-Bold', fontSize=8.5,
                            textColor=TEXT, leading=10.5)
HL_VAL_ST  = ParagraphStyle('hv', fontName='Helvetica-Bold', fontSize=12,
                            textColor=TEXT, leading=14, alignment=TA_LEFT)
HL_LBL_ST  = ParagraphStyle('hl', fontName='Helvetica', fontSize=7.5,
                            textColor=MUTED, leading=9, alignment=TA_LEFT)

CONTENT_W = letter[0] - 1.2 * inch   # 0.6 in margins each side

# ---------------------------------------------------------------- car data ----
CARS = [
    {
        "out": "2024 Porsche Cayenne S Coupe AWD.pdf",
        "title": "2024 Porsche Cayenne S Coupe AWD",
        "subtitle": "Sport Coupe  ·  Twin-Turbo V8  ·  468 hp / 600 Nm",
        "highlights": [
            ("Power", "468 hp"),
            ("Torque", "600 Nm"),
            ("Engine", "4.0L V8 TT"),
            ("Drivetrain", "AWD · 8-spd"),
            ("Fuel (comb.)", "13.6 L/100km"),
            ("Cargo (max)", "1,502 L"),
        ],
        "sections": [
            ("Engine & Performance", [
                ("Engine", "4.0L twin-turbo V8 (GDI, DOHC)"),
                ("Horsepower", "468 hp"),
                ("Torque", "600 Nm (443 lb-ft)"),
                ("Configuration", "V8, 4 valves / cylinder"),
                ("Transmission", "8-speed automatic (selectable mode; sequential shift, wheel paddles)"),
                ("Drivetrain", "Full-time all-wheel drive; selectable Terrain Modes"),
                ("Start / Stop", "Auto stop-start"),
                ("Steering", "Speed-sensitive electric power-assist; driver-selectable effort"),
                ("Suspension", "Adaptive ride — independent multi-link F/R, gas shocks, anti-roll bars"),
            ]),
            ("Fuel & Efficiency", [
                ("Fuel type", "Premium unleaded"),
                ("City", "15.7 L/100 km"),
                ("Highway", "11.0 L/100 km"),
                ("Combined", "13.6 L/100 km"),
                ("CO2 (combined)", "324 g/km"),
                ("Fuel tank", "90 L"),
                ("Emissions", "LEV3-SULEV125 / Tier 3 Bin 125"),
            ]),
            ("Dimensions & Weight", [
                ("Length", "4,930 mm"),
                ("Width", "1,983 mm"),
                ("Height", "1,678 mm"),
                ("Wheelbase", "2,895 mm"),
                ("Curb weight", "2,190 kg"),
                ("GVWR", "2,910 kg"),
                ("Payload", "720 kg"),
                ("Towing capacity", "3,500 kg"),
                ("Turning radius", "6.1 m"),
                ("Ground clearance", "212 mm"),
                ("Approach / departure", "25.3° / 22.3°"),
            ]),
            ("Capacity & Cargo", [
                ("Seating", "4 passengers"),
                ("Cargo — seats up", "592 L"),
                ("Cargo — seats folded", "1,502 L"),
            ]),
            ("Wheels, Tires & Brakes", [
                ("Front tire", "P255/55YR20 summer performance"),
                ("Rear tire", "P295/45YR20 summer performance"),
                ("Front wheel", "20 × 9.0 in grey aluminum"),
                ("Rear wheel", "20 × 10.5 in grey aluminum"),
                ("Spare", "Collapsible spare (aluminum wheel, under cargo floor)"),
                ("Brakes", "Ventilated disc — 410 mm F / 358 mm R; painted calipers"),
                ("Brake system", "4-channel ABS; electronic parking brake"),
            ]),
            ("Exterior", [
                ("Body", "Coupe, 4 doors; monotone paint; aluminum/steel body with side-impact beams"),
                ("Tailgate", "Power liftgate; auto-latching"),
                ("Aero", "Active grille shutters; power rear spoiler"),
                ("Headlights", "Adaptive LED (auto high-beam, auto-leveling, directional); LED DRL"),
                ("Lighting", "LED brake & cornering lights; perimeter approach lighting"),
                ("Mirrors", "Heated, power-folding, auto-dimming; tilt-down in reverse"),
                ("Glass", "First & second-row fixed glass sunroof; deep-tint windows"),
            ]),
            ("Interior & Comfort", [
                ("Front seats", "Leather sport buckets — 8-way power, heated; 3-position memory"),
                ("Rear seats", "Leather; 40-20-40 folding, reclining bench; centre armrest"),
                ("Seating", "4 passengers"),
                ("Climate", "Dual-zone automatic; rear climate ducts; cabin air filter"),
                ("Steering wheel", "Heated leather; power tilt/telescopic column"),
                ("Ambience", "Selectable ambient lighting; metal-look & piano-black accents"),
                ("Windows", "Power, one-touch up/down (front & rear)"),
            ]),
            ("Infotainment & Tech", [
                ("Display", "12.3 in touchscreen; 12.6 in digital gauge cluster"),
                ("Navigation", "Integrated, voice-activated; real-time traffic"),
                ("Audio", "10 speakers; 40 GB internal storage; FM/digital/satellite (3-mo trial)"),
                ("Connectivity", "Wireless streaming & mirroring; wireless smart-device charging"),
                ("Ports", "4 USB; 3 × 12 V outlets; mobile hotspot"),
                ("Smart features", "Built-in virtual assistant; mobile app; over-the-air updates"),
            ]),
            ("Safety & Driver Assist", [
                ("Airbags", "10 (front, side, knee, curtain)"),
                ("Forward aids", "Forward collision mitigation; pedestrian impact prevention"),
                ("Lane / speed", "Lane departure prevention; traffic-sign recognition + speed-limit assist"),
                ("Parking", "Front & rear parking sensors; rear camera"),
                ("Chassis control", "4-wheel ABS; ESC; brake assist; hill descent & start assist"),
                ("Security", "Immobilizer; security system; remote panic alarm"),
            ]),
            ("Warranty", [
                ("New vehicle", "48 months / 80,000 km"),
                ("Corrosion perforation", "144 months / unlimited"),
            ]),
        ],
    },
    {
        "out": "2023 Porsche 911 Carrera 4 GTS Coupe.pdf",
        "title": "2023 Porsche 911 Carrera 4 GTS Coupe",
        "subtitle": "Carrera 4 GTS  ·  Twin-Turbo Flat-Six  ·  473 hp / 570 Nm",
        "highlights": [
            ("Power", "473 hp"),
            ("Torque", "570 Nm"),
            ("Engine", "3.0L Flat-6 TT"),
            ("Drivetrain", "AWD · PDK 8-spd"),
            ("Fuel (comb.)", "12.1 L/100km"),
            ("Curb weight", "1,595 kg"),
        ],
        "sections": [
            ("Engine & Performance", [
                ("Engine", "3.0L twin-turbo flat-six (GDI, DOHC); rear-mounted"),
                ("Horsepower", "473 hp"),
                ("Torque", "570 Nm (420 lb-ft)"),
                ("Compression ratio", "10.2 : 1; governed 7,500 rpm"),
                ("Configuration", "H6, 4 valves / cylinder"),
                ("Transmission", "8-speed PDK (auto-shift manual; wheel paddles)"),
                ("Drivetrain", "Full-time all-wheel drive; electro-mechanical limited-slip diff"),
                ("Chassis highlights", "Rear-wheel steering; multi-mode exhaust"),
                ("Start / Stop", "Auto stop-start"),
                ("Steering", "Speed-sensitive electric power-assist; sport steering wheel"),
                ("Suspension", "Adaptive ride — strut F / multi-link R, gas shocks, active anti-roll bars"),
            ]),
            ("Fuel & Efficiency", [
                ("Fuel type", "Premium unleaded"),
                ("City", "13.8 L/100 km"),
                ("Highway", "10.1 L/100 km"),
                ("Combined", "12.1 L/100 km"),
                ("CO2 (combined)", "288 g/km"),
                ("Fuel tank", "67 L"),
                ("Emissions", "LEV3-ULEV70 / Tier 3 Bin 70"),
            ]),
            ("Dimensions & Weight", [
                ("Length", "4,533 mm"),
                ("Width", "1,852 mm"),
                ("Height", "1,301 mm"),
                ("Wheelbase", "2,450 mm"),
                ("Front / rear track", "1,589 / 1,557 mm"),
                ("Curb weight", "1,595 kg"),
                ("GVWR", "2,010 kg"),
                ("Payload", "406 kg"),
                ("Turning radius", "5.61 m"),
            ]),
            ("Capacity & Cargo", [
                ("Seating", "2 + 2 (4 passengers; rear buckets, 50-50 folding)"),
                ("Front trunk", "Manual frunk"),
                ("Cargo — seats folded", "264 L"),
                ("Max cargo", "396 L"),
            ]),
            ("Wheels, Tires & Brakes", [
                ("Front tire", "P245/35YR20 summer performance"),
                ("Rear tire", "P305/30YR21 summer performance"),
                ("Front wheel", "20 × 8.5 in black forged aluminum"),
                ("Rear wheel", "21 × 11.5 in black forged aluminum"),
                ("Wheel locks", "Wheel security locks"),
                ("Spare", "Tire mobility kit (no spare wheel)"),
                ("Brakes", "Cross-drilled/slotted ventilated disc — 408 mm F / 380 mm R; painted calipers"),
                ("Brake system", "4-channel ABS; electronic parking brake"),
            ]),
            ("Exterior", [
                ("Body", "Coupe, 2 doors; monotone paint; aluminum/steel/composite body with side-impact beams"),
                ("Aero", "Power rear spoiler; rear wing; active grille shutters"),
                ("Headlights", "Adaptive LED (auto high-beam, auto-leveling, directional); LED DRL"),
                ("Lighting", "LED brake & cornering lights; perimeter approach lighting"),
                ("Mirrors", "Heated, power-folding, auto-dimming"),
                ("Trim", "Rocker panel extensions; front & rear tow hooks"),
                ("Tires", "20 in / 21 in staggered forged summer package"),
            ]),
            ("Interior & Comfort", [
                ("Front seats", "Leather & simulated-suede sport buckets — 6-way, heated"),
                ("Rear seats", "2 + 2; 50-50 folding rear buckets"),
                ("Steering wheel", "Heated leather sport; manual tilt/telescopic"),
                ("Climate", "Dual-zone automatic; residual heat recirc; cabin air filter"),
                ("Ambience", "Ambient lighting; metal-look accents; leather/aluminum shifter"),
                ("Glass", "Light-tint laminated glass; power one-touch windows"),
                ("Flooring", "Carpet front & rear mats"),
            ]),
            ("Infotainment & Tech", [
                ("Display", "10.9 in touchscreen; 7.0 in gauge cluster; 3 first-row displays"),
                ("Navigation", "Integrated, voice-activated; real-time traffic & weather"),
                ("Audio", "8 speakers with amplifier & DSP; performance data recorder (video)"),
                ("Connectivity", "Wireless streaming & mirroring"),
                ("Ports", "2 USB; 1 × 12 V outlet; mobile hotspot"),
                ("Smart features", "Built-in virtual assistant; over-the-air updates"),
            ]),
            ("Safety & Driver Assist", [
                ("Airbags", "6 (front, side, curtain)"),
                ("Forward aids", "Forward collision mitigation; pedestrian impact prevention"),
                ("Parking", "Front & rear parking sensors; rear camera"),
                ("Chassis control", "4-wheel ABS; ESC; brake assist; hill start assist"),
                ("Security", "Immobilizer; security system; tire mobility kit"),
            ]),
            ("Warranty", [
                ("New vehicle", "48 months / 80,000 km"),
                ("Corrosion perforation", "144 months / unlimited"),
            ]),
        ],
    },
]


# ---------------------------------------------------------------- builders ----
def _accent_rule():
    """Thin red rule under the title."""
    t = Table([[' ']], colWidths=[CONTENT_W], rowHeights=[2.2])
    t.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), ACCENT),
                           ('LEFTPADDING', (0, 0), (-1, -1), 0),
                           ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                           ('TOPPADDING', (0, 0), (-1, -1), 0),
                           ('BOTTOMPADDING', (0, 0), (-1, -1), 0)]))
    return t


def _highlights_block(items):
    """3x2 grid of key-stat cards."""
    cells = []
    for label, value in items:
        cells.append([
            Paragraph(value, HL_VAL_ST),
            Spacer(1, 1),
            Paragraph(label.upper(), HL_LBL_ST),
        ])
    rows = [cells[0:3], cells[3:6]]
    col_w = CONTENT_W / 3.0
    t = Table(rows, colWidths=[col_w] * 3)
    t.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), CARD_BG),
        ('BOX', (0, 0), (-1, -1), 0.5, RULE),
        ('INNERGRID', (0, 0), (-1, -1), 0.5, RULE),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 9),
        ('RIGHTPADDING', (0, 0), (-1, -1), 9),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
    ]))
    return t


def _section_block(title, rows):
    bar = Table([[Paragraph(title, SECT_ST)]], colWidths=[CONTENT_W])
    bar.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), SECTION_BG),
        ('LEFTPADDING', (0, 0), (-1, -1), 7),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
    ]))

    data = [[Paragraph(l, LBL_ST), Paragraph(v, VAL_ST)] for l, v in rows]
    body = Table(data, colWidths=[CONTENT_W * 0.34, CONTENT_W * 0.66])
    body.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 7),
        ('RIGHTPADDING', (0, 0), (-1, -1), 7),
        ('TOPPADDING', (0, 0), (-1, -1), 2),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ('ROWBACKGROUNDS', (0, 0), (-1, -1), [white, ZEBRA]),
        ('LINEBELOW', (0, 0), (-1, -2), 0.4, RULE),
    ]))
    return KeepTogether([bar, body, Spacer(1, 5)])


def _on_page(canvas, doc):
    canvas.saveState()
    w, h = letter
    canvas.setFont('Helvetica', 7)
    canvas.setFillColor(HexColor('#9a9a9a'))
    canvas.drawString(0.6 * inch, 0.36 * inch,
                      "Vehicle specifications as-equipped, per factory build data. Metric units.")
    canvas.drawRightString(w - 0.6 * inch, 0.36 * inch,
                           "Page %d" % canvas.getPageNumber())
    if canvas.getPageNumber() > 1:
        canvas.setFont('Helvetica-Oblique', 8)
        canvas.setFillColor(HexColor('#9a9a9a'))
        canvas.drawRightString(w - 0.6 * inch, h - 0.4 * inch, doc.model_title)
    canvas.restoreState()


def build(car):
    doc = SimpleDocTemplate(
        car["out"], pagesize=letter,
        leftMargin=0.6 * inch, rightMargin=0.6 * inch,
        topMargin=0.55 * inch, bottomMargin=0.6 * inch,
        title=car["title"], author="Spec Sheet",
    )
    doc.model_title = car["title"]

    flow = [
        Paragraph(car["title"], TITLE_ST),
        _accent_rule(),
        Spacer(1, 3),
        Paragraph(car["subtitle"], SUB_ST),
        Spacer(1, 7),
        _highlights_block(car["highlights"]),
        Spacer(1, 9),
    ]
    for title, rows in car["sections"]:
        flow.append(_section_block(title, rows))

    doc.build(flow, onFirstPage=_on_page, onLaterPages=_on_page)
    import os
    return os.path.getsize(car["out"])


if __name__ == "__main__":
    import os
    here = os.path.dirname(os.path.abspath(__file__))
    os.chdir(here)
    for car in CARS:
        size = build(car)
        print("wrote %-45s %6.1f KB" % (car["out"], size / 1024.0))
