"""Digital hand-off / sign-off documentation for B2B fleet drivers — a
fleet company enables/relabels a fixed catalog of fields (not a full form
builder) into named templates ("Trip Start Inspection", etc.), drivers fill
out the enabled fields and sign with a finger/mouse, and the company gets a
searchable log of submissions. Standalone — not tied to a customer order,
same as a vehicle handover or fuel-stop checklist wouldn't be."""

from accounts.supabase_client import get_client

# Fixed, Python-defined catalog — a company can enable/disable and relabel
# any of these per template, but can't add new keys. 'type' drives how the
# driver-facing form renders the field and how a submitted value validates.
FIELD_CATALOG = {
    'vehicle_condition': {'type': 'select', 'options': ['good', 'fair', 'poor', 'needs_repair'], 'default_label_key': 'signoff_field_vehicle_condition'},
    'odometer_km': {'type': 'number', 'default_label_key': 'signoff_field_odometer_km'},
    'cargo_condition': {'type': 'select', 'options': ['good', 'damaged', 'missing_items'], 'default_label_key': 'signoff_field_cargo_condition'},
    'tires_ok': {'type': 'checkbox', 'default_label_key': 'signoff_field_tires_ok'},
    'lights_ok': {'type': 'checkbox', 'default_label_key': 'signoff_field_lights_ok'},
    'notes': {'type': 'textarea', 'default_label_key': 'signoff_field_notes'},
    'custom_field_1': {'type': 'text', 'default_label_key': 'signoff_field_custom_field_1'},
    'custom_field_2': {'type': 'text', 'default_label_key': 'signoff_field_custom_field_2'},
}


def get_templates_for_company(company_id, active_only=False):
    query = get_client().table('pickker_signoff_templates').select('*').eq('company_id', company_id)
    if active_only:
        query = query.eq('is_active', True)
    return query.order('created_at', desc=True).execute().data


def get_template(template_id):
    resp = get_client().table('pickker_signoff_templates').select('*').eq('id', template_id).execute()
    return resp.data[0] if resp.data else None


def create_template(company_id, name, fields_config):
    resp = get_client().table('pickker_signoff_templates').insert({
        'company_id': company_id, 'name': name.strip(), 'fields_config': fields_config, 'is_active': True,
    }).execute()
    return resp.data[0] if resp.data else None


def update_template(template_id, name, fields_config):
    get_client().table('pickker_signoff_templates').update({
        'name': name.strip(), 'fields_config': fields_config,
    }).eq('id', template_id).execute()


def set_template_active(template_id, is_active):
    get_client().table('pickker_signoff_templates').update({'is_active': is_active}).eq('id', template_id).execute()


def get_active_templates_for_driver(picker_id):
    """Looks up the driver's own company via their profile, then returns
    that company's active templates — a driver never needs to know their
    company_id directly."""
    profile_resp = get_client().table('pickker_picker_profiles').select('company_id').eq('user_id', picker_id).execute()
    company_id = profile_resp.data[0]['company_id'] if profile_resp.data else None
    if not company_id:
        return []
    return get_templates_for_company(company_id, active_only=True)


def create_submission(template_id, company_id, picker_id, values, signature_data_url, truck_id=None):
    resp = get_client().table('pickker_signoff_submissions').insert({
        'template_id': template_id,
        'company_id': company_id,
        'picker_id': picker_id,
        'truck_id': truck_id,
        'values': values,
        'signature_data_url': signature_data_url,
    }).execute()
    return resp.data[0] if resp.data else None


def get_submissions_for_company(company_id, limit=100):
    return (
        get_client().table('pickker_signoff_submissions').select('*')
        .eq('company_id', company_id).order('created_at', desc=True).limit(limit).execute().data
    )
