"""Onboarding progress helper — computes steps from existing DB data."""

import os


def compute_onboarding_steps(user, user_companies, app_root):
    """Compute onboarding progress for dashboard widget.

    Args:
        user: Current User object (Flask-Login)
        user_companies: List of UserCompany objects (with .company loaded)
        app_root: current_app.root_path for file checks

    Returns:
        dict with steps, completed, total, percentage, all_complete
    """
    company = user_companies[0].company if user_companies else None

    steps = [
        {
            'key': 'registration',
            'label': 'Rejestracja konta',
            'completed': True,
            'responsible': 'auto',
            'responsible_label': 'Automatyczne',
        },
        {
            'key': 'email_verified',
            'label': 'Weryfikacja adresu e-mail',
            'completed': getattr(user, 'is_verified', False),
            'responsible': 'member',
            'responsible_label': 'Ty',
        },
        {
            'key': 'company_linked',
            'label': 'Powiązanie z firmą',
            'completed': len(user_companies) > 0,
            'responsible': 'office',
            'responsible_label': 'Sekretariat',
        },
        {
            'key': 'basic_data',
            'label': 'Dane podstawowe firmy',
            'completed': bool(
                company
                and company.name
                and getattr(company, 'nip', None)
                and getattr(company, 'address_city', None)
            ),
            'responsible': 'office',
            'responsible_label': 'Sekretariat',
        },
        {
            'key': 'description',
            'label': 'Opis i oferta firmy',
            'completed': bool(
                company
                and getattr(company, 'description_full', None)
                and getattr(company, 'services_offered', None)
            ),
            'responsible': 'member',
            'responsible_label': 'Ty',
            'action_url': f'/company/{company.id}/edit' if company else None,
        },
        {
            'key': 'logo',
            'label': 'Logo firmy',
            'completed': bool(
                company
                and getattr(company, 'slug', None)
                and os.path.exists(
                    os.path.join(app_root, 'static', 'img', 'companies', f'{company.slug}.webp')
                )
            ),
            'responsible': 'both',
            'responsible_label': 'Ty / Sekretariat',
            'action_url': f'/company/{company.id}/edit' if company else None,
        },
    ]

    completed = sum(1 for s in steps if s['completed'])
    total = len(steps)

    return {
        'steps': steps,
        'completed': completed,
        'total': total,
        'percentage': round(completed / total * 100) if total else 0,
        'all_complete': completed == total,
    }
