#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Генератор конфигурации шин для Assetto Corsa с правильной автомобильной формулой
WIDTH: 50, 100, 200, 250, 300 мм
Profile: 35%, 45%, 55% от ширины  
Rim sizes: R16-R22
Типы: Drift (D), Realistic (R), Grip (G)
Формула: RADIUS = (ширина × профиль%) + (диск × 25.4 / 2)
         RIM_RADIUS = (диск + 1.5) × 25.4 / 2 / 1000
"""

import math

def calculate_tire_dimensions(width_mm, profile_percent, rim_size_inches):
    """Calculate tire dimensions based on automotive tire sizing formula"""
    # RADIUS = (width * profile_percentage) + (rim_size * 25.4 / 2)
    # Convert to meters
    tire_radius_mm = (width_mm * profile_percent / 100.0) + (rim_size_inches * 25.4 / 2)
    tire_radius = tire_radius_mm / 1000.0
    
    # RIM_RADIUS = (rim_size + 1.5) * 25.4 / 2 / 1000
    rim_radius = (rim_size_inches + 1.5) * 25.4 / 2 / 1000.0
    
    return rim_radius, tire_radius

def generate_tire_config():
    """Generate complete tire configuration"""
    
    # Tire parameters for each type
    tire_types = {
        'drift': {
            'name': 'Drift',
            'short_name': 'D',
            'type_hint': 'TREADED',
            'wear_curve': 'tire_wear_dy_road_65.lut',
            'rolling_resistance_0': 8,
            'friction_limit_angle': 6.18,
            'dx_curve': 'tire_D_265_DX.lut',
            'dy_curve': 'tire_D_265_DY.lut',
            'falloff_level_curve': 'tire_heat_road_60_level.lut',
            'falloff_speed_curve': 'tire_heat_road_60_speed.lut',
            'performance_curve': 'tire_heat_road_60_mu.lut'
        },
        'realistic': {
            'name': 'Realistic',
            'short_name': 'R', 
            'type_hint': 'RACING_TREADED',
            'wear_curve': 'tire_wear_dy_road_50.lut',
            'rolling_resistance_0': 13,
            'friction_limit_angle': 6.38,
            'dx_curve': 'tire_M_265_DX.lut',
            'dy_curve': 'tire_M_265_DY.lut',
            'falloff_level_curve': 'tire_heat_road_70_level.lut',
            'falloff_speed_curve': 'tire_heat_road_70_speed.lut',
            'performance_curve': 'tire_heat_road_70_mu.lut'
        },
        'grip': {
            'name': 'Grip',
            'short_name': 'G',
            'type_hint': 'SEMISLICK',
            'wear_curve': 'tire_wear_dy_road_30.lut',
            'rolling_resistance_0': 21,
            'friction_limit_angle': 6.88,
            'dx_curve': 'tire_G_265_DX.lut',
            'dy_curve': 'tire_G_265_DY.lut',
            'falloff_level_curve': 'tire_heat_road_80_level.lut',
            'falloff_speed_curve': 'tire_heat_road_80_speed.lut',
            'performance_curve': 'tire_heat_road_80_mu.lut'
        }
    }
    
    # Start with header
    config = """[HEADER]
VERSION=10 ; emi 2.11
; Built by Ini-F arcade calculator, hope you like it :)

[_EXTENSION]
PRACTICAL_TEMP_RATIO=0.8
USE_NEW_RR_SLIP=1
USE_RELAX_LENGTH_ON_FORCE=1
EXTENDED_RAYTRACING=0
LATERAL_RAYS=1
LONGITUDINAL_RAYS=1
MAX_RAY_ANGLE=60
MAX_RAY_WIDTH_RATIO=1.3
DISABLE_RAY_DOUBLING=0

[THERMAL_MODEL]
VERSION=2

[VIRTUALKM]
USE_LOAD=1

[EXPLOSION]
TEMPERATURE=300

[ADDITIONAL1]
BLANKETS_TEMP=40

[COMPOUND_DEFAULT]
INDEX=1

"""
    
    # Generate base FRONT and REAR sections (default Drift)
    config += generate_base_sections()
    
    # Generate all tire combinations
    tire_index = 1
    lua_table_data = []
    
    widths_mm = [50, 100, 200, 250, 300]  # in millimeters
    profile_percentages = [35, 45, 55]  # percentage of width
    rim_sizes = list(range(16, 23))  # R16 to R22
    
    for width_mm in widths_mm:
        for profile_percent in profile_percentages:
            for rim_size in rim_sizes:
                rim_radius, tire_radius = calculate_tire_dimensions(width_mm, profile_percent, rim_size)
                
                # Convert width to meters for INI file
                width_m = width_mm / 1000.0
                
                for tire_type, params in tire_types.items():
                    # Create tire name
                    tire_name = f"{params['name']} {width_mm}/{profile_percent}/R{rim_size}"
                    
                    # Generate sections
                    config += generate_tire_section('FRONT', tire_index, params, width_m, tire_radius, rim_radius, tire_name)
                    config += generate_tire_section('REAR', tire_index, params, width_m, tire_radius, rim_radius, tire_name)
                    config += generate_thermal_section('FRONT', tire_index, params)
                    config += generate_thermal_section('REAR', tire_index, params)
                    config += generate_thermal2_section('FRONT', tire_index)
                    config += generate_thermal2_section('REAR', tire_index)
                    
                    # Add to lua table data
                    lua_table_data.append({
                        'id': tire_index,
                        'type': params['short_name'],
                        'width': width_mm,
                        'profile': profile_percent,
                        'rim': rim_size
                    })
                    
                    tire_index += 1
    
    # Generate Lua table
    lua_table = generate_lua_table(lua_table_data)
    
    return config, lua_table

def generate_base_sections():
    """Generate base FRONT and REAR sections"""
    return """[FRONT]
NAME=Drift
SHORT_NAME=D
TYPE_HINT=TREADED
WIDTH=0.25
RADIUS=0.348
RIM_RADIUS=0.2542
ANGULAR_INERTIA=1.5
DAMP=968
RATE=309064
CAMBER_SPRING_MULT=tire_camber_spring_k_265.lut

DY0=1.3027
DY1=-0.048
DX0=1.3115
DX1=-0.046
FLEX=0.000684
XMU=0.27

WEAR_CURVE=tire_wear_dy_road_65.lut
SPEED_SENSITIVITY=0.00106
RELAXATION_LENGTH=0.056
ROLLING_RESISTANCE_0=8
ROLLING_RESISTANCE_1=0.002058
ROLLING_RESISTANCE_SLIP=813

CAMBER_GAIN=0.113
DCAMBER_0=1.1
DCAMBER_1=-13
DCAMBER_LUT=tire_camber_dy_6deg.lut
DCAMBER_LUT_SMOOTH=1
DX_CAMBER_REF=3
DX_CAMBER_MULT=0.98
FRICTION_LIMIT_ANGLE=6.18

CX_MULT=1.10
BRAKE_DX_MOD=-0.02

PRESSURE_STATIC=34
PRESSURE_SPRING_GAIN=8796
PRESSURE_FLEX_GAIN=-0.25
PRESSURE_RR_GAIN=0.40
PRESSURE_D_GAIN=0.003
PRESSURE_IDEAL=39.5
FZ0=3000
LS_EXPX=0.5
LS_EXPY=0.5
DX_REF=0.5
DY_REF=0.5
DX_CURVE=tire_D_265_DX.lut
DY_CURVE=tire_D_265_DY.lut
FLEX_GAIN=0.07

FALLOFF_LEVEL_CURVE=tire_heat_road_60_level.lut
FALLOFF_SPEED_CURVE=tire_heat_road_60_speed.lut
FALLOFF_LEVEL=0.81
FALLOFF_SPEED=13

RADIUS_ANGULAR_K=0.01
RADIUS_ANGULAR_K_2=0.05
ROLLING_RADIUS_MULT=0.1

[THERMAL_FRONT]
SURFACE_TRANSFER=0.98
PATCH_TRANSFER=0.002
CORE_TRANSFER=0
INTERNAL_CORE_TRANSFER=0
FRICTION_K=0.0084
ROLLING_K=0
PERFORMANCE_CURVE=tire_heat_road_60_mu.lut
GRAIN_GAMMA=1
GRAIN_GAIN=0
BLISTER_GAMMA=1
BLISTER_GAIN=0
COOL_FACTOR=5
SURFACE_ROLLING_K=0.04

[THERMAL2_FRONT]
CARCASS_ROLLING_K=0.25
BRAKE_TO_CORE=0
SURFACE_TO_AMBIENT=0.0292
SURFACE_TO_CARCASS=0.033
CARCASS_TO_SURFACE=0.125
CARCASS_TO_CORE=0.0050
CORE_TO_CARCASS=0.0010
CORE_TO_AMBIENT=0.0015
FRICTION_TEMP_K=1

[REAR]
NAME=Drift
SHORT_NAME=D
TYPE_HINT=TREADED
WIDTH=0.25
RADIUS=0.348
RIM_RADIUS=0.2542
ANGULAR_INERTIA=1.5
DAMP=968
RATE=309064
CAMBER_SPRING_MULT=tire_camber_spring_k_265.lut

DY0=1.3027
DY1=-0.048
DX0=1.3115
DX1=-0.046
FLEX=0.000684
XMU=0.27

WEAR_CURVE=tire_wear_dy_road_65.lut
SPEED_SENSITIVITY=0.00106
RELAXATION_LENGTH=0.056
ROLLING_RESISTANCE_0=8
ROLLING_RESISTANCE_1=0.002058
ROLLING_RESISTANCE_SLIP=813

CAMBER_GAIN=0.113
DCAMBER_0=1.1
DCAMBER_1=-13
DCAMBER_LUT=tire_camber_dy_6deg.lut
DCAMBER_LUT_SMOOTH=1
DX_CAMBER_REF=3
DX_CAMBER_MULT=0.98
FRICTION_LIMIT_ANGLE=6.18

CX_MULT=1.10
BRAKE_DX_MOD=-0.02

PRESSURE_STATIC=34
PRESSURE_SPRING_GAIN=8796
PRESSURE_FLEX_GAIN=-0.25
PRESSURE_RR_GAIN=0.40
PRESSURE_D_GAIN=0.003
PRESSURE_IDEAL=39.5

FZ0=3000
LS_EXPX=0.5
LS_EXPY=0.5
DX_REF=0.5
DY_REF=0.5
DX_CURVE=tire_D_265_DX.lut
DY_CURVE=tire_D_265_DY.lut
FLEX_GAIN=0.07

FALLOFF_LEVEL_CURVE=tire_heat_road_60_level.lut
FALLOFF_SPEED_CURVE=tire_heat_road_60_speed.lut
FALLOFF_LEVEL=0.81
FALLOFF_SPEED=13

RADIUS_ANGULAR_K=0.01
RADIUS_ANGULAR_K_2=0.05
ROLLING_RADIUS_MULT=0.1

[THERMAL_REAR]
SURFACE_TRANSFER=0.98
PATCH_TRANSFER=0.002
CORE_TRANSFER=0
INTERNAL_CORE_TRANSFER=0
FRICTION_K=0.0084
ROLLING_K=0
PERFORMANCE_CURVE=tire_heat_road_60_mu.lut
GRAIN_GAMMA=1
GRAIN_GAIN=0
BLISTER_GAMMA=1
BLISTER_GAIN=0
COOL_FACTOR=5
SURFACE_ROLLING_K=0.04

[THERMAL2_REAR]
CARCASS_ROLLING_K=0.25
BRAKE_TO_CORE=0
SURFACE_TO_AMBIENT=0.0292
SURFACE_TO_CARCASS=0.033
CARCASS_TO_SURFACE=0.125
CARCASS_TO_CORE=0.0050
CORE_TO_CARCASS=0.0010
CORE_TO_AMBIENT=0.0015
FRICTION_TEMP_K=1

"""

def generate_tire_section(position, index, params, width, radius, rim_radius, tire_name):
    """Generate tire section"""
    section_name = f"{position}_{index}"
    
    return f"""[{section_name}]
NAME={tire_name}
SHORT_NAME={params['short_name']}
TYPE_HINT={params['type_hint']}
WIDTH={width:.4f}
RADIUS={radius:.6f}
RIM_RADIUS={rim_radius:.6f}
ANGULAR_INERTIA=1.5
DAMP=968
RATE=309064
CAMBER_SPRING_MULT=tire_camber_spring_k_265.lut

DY0=1.3027
DY1=-0.048
DX0=1.3115
DX1=-0.046
FLEX=0.000684
XMU=0.27

WEAR_CURVE={params['wear_curve']}
SPEED_SENSITIVITY=0.00106
RELAXATION_LENGTH=0.056
ROLLING_RESISTANCE_0={params['rolling_resistance_0']}
ROLLING_RESISTANCE_1=0.002058
ROLLING_RESISTANCE_SLIP=813

CAMBER_GAIN=0.113
DCAMBER_0=1.1
DCAMBER_1=-13
DCAMBER_LUT=tire_camber_dy_6deg.lut
DCAMBER_LUT_SMOOTH=1
DX_CAMBER_REF=3
DX_CAMBER_MULT=0.98
FRICTION_LIMIT_ANGLE={params['friction_limit_angle']}

CX_MULT=1.10
BRAKE_DX_MOD=-0.02

PRESSURE_STATIC=34
PRESSURE_SPRING_GAIN=8796
PRESSURE_FLEX_GAIN=-0.25
PRESSURE_RR_GAIN=0.40
PRESSURE_D_GAIN=0.003
PRESSURE_IDEAL=39.5
FZ0=3000
LS_EXPX=0.5
LS_EXPY=0.5
DX_REF=0.5
DY_REF=0.5
DX_CURVE={params['dx_curve']}
DY_CURVE={params['dy_curve']}
FLEX_GAIN=0.07

FALLOFF_LEVEL_CURVE={params['falloff_level_curve']}
FALLOFF_SPEED_CURVE={params['falloff_speed_curve']}
FALLOFF_LEVEL=0.81
FALLOFF_SPEED=13

RADIUS_ANGULAR_K=0.01
RADIUS_ANGULAR_K_2=0.05
ROLLING_RADIUS_MULT=0.1

"""

def generate_thermal_section(position, index, params):
    """Generate thermal section"""
    section_name = f"THERMAL_{position}_{index}"
    
    return f"""[{section_name}]
SURFACE_TRANSFER=0.98
PATCH_TRANSFER=0.002
CORE_TRANSFER=0
INTERNAL_CORE_TRANSFER=0
FRICTION_K=0.0084
ROLLING_K=0
PERFORMANCE_CURVE={params['performance_curve']}
GRAIN_GAMMA=1
GRAIN_GAIN=0
BLISTER_GAMMA=1
BLISTER_GAIN=0
COOL_FACTOR=5
SURFACE_ROLLING_K=0.04

"""

def generate_thermal2_section(position, index):
    """Generate thermal2 section"""
    section_name = f"THERMAL2_{position}_{index}"
    
    return f"""[{section_name}]
CARCASS_ROLLING_K=0.25
BRAKE_TO_CORE=0
SURFACE_TO_AMBIENT=0.0292
SURFACE_TO_CARCASS=0.033
CARCASS_TO_SURFACE=0.125
CARCASS_TO_CORE=0.0050
CORE_TO_CARCASS=0.0010
CORE_TO_AMBIENT=0.0015
FRICTION_TEMP_K=1

"""

def generate_lua_table(data):
    """Generate Lua table for tire configurations"""
    lua_table = """-- Tire configuration table for Lua
tires = {
"""
    
    for item in data:
        lua_table += f"    [{item['id']}] = \"{item['type']}-{item['width']}/{item['profile']}/R{item['rim']}\",\n"
    
    lua_table += "}\n"
    return lua_table

def main():
    """Main function"""
    print("Генерация новой конфигурации шин для Assetto Corsa...")
    
    # Calculate total combinations
    widths = 5  # 50, 100, 200, 250, 300 mm
    profile_percentages = 3  # 35%, 45%, 55%
    rim_sizes = 7  # R16-R22
    tire_types = 3  # Drift, Realistic, Grip
    total_variants = widths * profile_percentages * rim_sizes * tire_types
    
    print(f"Создается конфигураций:")
    print(f"  Ширины: {widths} размеров (50, 100, 200, 250, 300мм)")
    print(f"  Профили: {profile_percentages} размера (35%, 45%, 55%)")
    print(f"  Диски: {rim_sizes} размеров (R16-R22)")
    print(f"  Типы: {tire_types} типа (Drift, Realistic, Grip)")
    print(f"  ИТОГО: {total_variants:,} вариантов шин")
    
    # Generate configurations
    config, lua_table = generate_tire_config()
    
    # Save files
    ini_file = "tyres.ini"
    lua_file = "tire_table.lua"
    
    with open(ini_file, 'w', encoding='utf-8') as f:
        f.write(config)
    
    with open(lua_file, 'w', encoding='utf-8') as f:
        f.write(lua_table)
    
    print(f"\nФайлы созданы:")
    print(f"  {ini_file} - конфигурация шин")
    print(f"  {lua_file} - таблица для Lua")
    
    print("\nПримеры размеров (ширина/профиль%/диск):")
    print("  ID 1: D-50/35/R16")
    print("  ID 105: R-100/45/R18") 
    print("  ID 315: G-300/55/R22")
    
    print("\nПример расчета 305/45/R19:")
    example_radius = (305 * 0.45) + (19 * 25.4 / 2)
    example_rim = (19 + 1.5) * 25.4 / 2 / 1000
    print(f"  RADIUS = (305 * 0.45) + (19 * 25.4 / 2) = {example_radius:.1f}мм = {example_radius/1000:.6f}м")
    print(f"  RIM_RADIUS = (19 + 1.5) * 25.4 / 2 / 1000 = {example_rim:.6f}м")

if __name__ == "__main__":
    main() 