<?php

declare(strict_types=1);

final class MyronUserAgentClassifier
{
    /**
     * @return array{device_type:string,browser_family:string,os_family:string,ua_family:string}
     */
    public function classify(string $userAgent): array
    {
        $ua = strtolower($userAgent);
        $device = 'desktop';
        if ($ua === '') {
            $device = 'desktop';
        } elseif (str_contains($ua, 'ipad') || str_contains($ua, 'tablet')) {
            $device = 'tablet';
        } elseif (str_contains($ua, 'mobi') || str_contains($ua, 'iphone') || str_contains($ua, 'android')) {
            $device = str_contains($ua, 'android') && !str_contains($ua, 'mobile') ? 'tablet' : 'mobile';
        }

        $browser = match (true) {
            str_contains($ua, 'edg/') || str_contains($ua, 'edge/') => 'Edge',
            str_contains($ua, 'opr/') || str_contains($ua, 'opera') => 'Opera',
            str_contains($ua, 'firefox/') => 'Firefox',
            str_contains($ua, 'chrome/') || str_contains($ua, 'crios/') => 'Chrome',
            str_contains($ua, 'safari/') => 'Safari',
            default => 'Other',
        };

        $os = match (true) {
            str_contains($ua, 'windows') => 'Windows',
            str_contains($ua, 'iphone') || str_contains($ua, 'ipad') || str_contains($ua, 'ios') => 'iOS',
            str_contains($ua, 'android') => 'Android',
            str_contains($ua, 'mac os') || str_contains($ua, 'macintosh') => 'macOS',
            str_contains($ua, 'linux') => 'Linux',
            default => 'Other',
        };

        return [
            'device_type' => $device,
            'browser_family' => $browser,
            'os_family' => $os,
            'ua_family' => $browser . '/' . $os . '/' . $device,
        ];
    }
}
