<?php
if (!defined('ABSPATH')) exit;

if (!function_exists('asana_automator_bootstrap_normalize_name')) {
    function asana_automator_bootstrap_normalize_name(string $name): string {
        $name = strtolower(trim($name));
        $name = preg_replace('/\s*\([^\)]*\)/', '', (string)$name);
        $name = preg_replace('/[^a-z0-9\s\/\-]+/', ' ', (string)$name);
        $name = preg_replace('/\s+/', ' ', (string)$name);
        return trim((string)$name);
    }
}

if (!function_exists('asana_automator_bootstrap_find_field')) {
    function asana_automator_bootstrap_find_field(array $fields, array $needles): ?array {
        foreach ($fields as $field) {
            $name = asana_automator_bootstrap_normalize_name((string)($field['name'] ?? ''));
            foreach ($needles as $needle) {
                if (strpos($name, $needle) !== false) {
                    return $field;
                }
            }
        }
        return null;
    }
}

if (!function_exists('asana_automator_bootstrap_merge_aliases')) {
    function asana_automator_bootstrap_merge_aliases(array $base, array $extra): array {
        foreach ($extra as $from => $to) {
            $from = trim((string)$from);
            $to = trim((string)$to);
            if ($from === '' || $to === '') {
                continue;
            }
            $base[$from] = $to;
        }
        return $base;
    }
}

if (!function_exists('asana_automator_bootstrap_fetch_project_fields')) {
    function asana_automator_bootstrap_fetch_project_fields(string $project_gid, string $token): array {
        if ($project_gid === '' || $token === '') {
            return [];
        }

        $url = "https://app.asana.com/api/1.0/projects/{$project_gid}/custom_field_settings"
            . '?opt_fields=custom_field.gid,custom_field.name,custom_field.type,custom_field.enum_options.gid,custom_field.enum_options.name,custom_field.enum_options.enabled';

        $res = wp_remote_get($url, [
            'headers' => ['Authorization' => 'Bearer ' . $token],
        ]);

        if (is_wp_error($res)) {
            return [];
        }

        $body = json_decode(wp_remote_retrieve_body($res), true);
        $settings = (array)($body['data'] ?? []);

        $fields = [];
        foreach ($settings as $setting) {
            if (!empty($setting['custom_field']) && is_array($setting['custom_field'])) {
                $fields[] = $setting['custom_field'];
            }
        }

        return $fields;
    }
}

if (!function_exists('asana_automator_bootstrap_build_rules')) {
    function asana_automator_bootstrap_build_rules(array $fields): array {
        $rules = [];

        $site_field = asana_automator_bootstrap_find_field($fields, ['site']);
        if (!empty($site_field['gid'])) {
            $aliases = [];
            foreach ((array)($site_field['enum_options'] ?? []) as $opt) {
                if (isset($opt['enabled']) && !$opt['enabled']) {
                    continue;
                }
                $full = trim((string)($opt['name'] ?? ''));
                if ($full === '') {
                    continue;
                }
                $short = trim((string)preg_replace('/\s*,\s*.*/', '', $full));
                if ($short !== '' && strcasecmp($short, $full) !== 0) {
                    $aliases[$short] = $full;
                }
            }

            // Service-catalog site names that differ from Asana enum names.
            $aliases = asana_automator_bootstrap_merge_aliases($aliases, [
                "41 O'Connell Terrace" => "41 O'Connell Tce, Bowen Hills",
                '315 Brunswick Street' => 'The Precinct, Brunswick Street, Fortitude Valley',
                '317 Edward Street, 1C' => '317 1C Edward Street, Brisbane City',
                '317 Edward Street 1C' => '317 1C Edward Street, Brisbane City',
                '317 Edward Street, 1D' => '317 1D Edward Street, Brisbane City',
                '317 Edward Street 1D' => '317 1D Edward Street, Brisbane City',
            ]);

            $rules[] = [
                'source_label' => 'Site',
                'target_field_gid' => (string)$site_field['gid'],
                'target_type' => 'enum',
                'aliases' => $aliases,
            ];
        }

        $level_field = asana_automator_bootstrap_find_field($fields, ['level']);
        if (!empty($level_field['gid'])) {
            $rules[] = [
                'source_labels' => ['Level', 'Level 108 Wickham', 'Level 100 Wickham', 'Level 33 Charlotte', 'Level 15 Butterfield'],
                'target_field_gid' => (string)$level_field['gid'],
                'target_type' => 'enum',
                'aliases' => [
                    'G' => 'Ground floor',
                ],
            ];
        }

        $area_field = asana_automator_bootstrap_find_field($fields, ['area/location/room', 'area location room', 'location', 'room']);
        if (!empty($area_field['gid'])) {
            $rules[] = [
                'source_labels' => ['Location Detail', 'Area/Location/Room', 'Location', 'Area', 'Area (Other)'],
                'target_field_gid' => (string)$area_field['gid'],
                'target_type' => 'enum',
                'aliases' => [
                    'First aid room' => 'First/aid room',
                    'Family / Mothers room' => 'Family/Mothers room',
                    'All access toilet/pwd' => 'PWD toilet',
                ],
            ];
        }

        $room_ws_field = asana_automator_bootstrap_find_field($fields, ['room/office/workstation number', 'room office workstation number']);
        if (!empty($room_ws_field['gid'])) {
            $rules[] = [
                'source_labels' => ['Room/Workstation #', 'Room Or Workstation Number', 'Room/Office/Workstation number'],
                'target_field_gid' => (string)$room_ws_field['gid'],
                'target_type' => 'text',
            ];
        }

        $incident_field = asana_automator_bootstrap_find_field($fields, ['incident type']);
        if (!empty($incident_field['gid'])) {
            $rules[] = [
                'source_label' => 'Incident Type',
                'target_field_gid' => (string)$incident_field['gid'],
                'target_type' => 'enum',
            ];
        }

        $disruption_field = asana_automator_bootstrap_find_field($fields, ['disruption']);
        if (!empty($disruption_field['gid'])) {
            $rules[] = [
                'source_labels' => ['Urgency', 'Disruption'],
                'target_field_gid' => (string)$disruption_field['gid'],
                'target_type' => 'enum',
            ];
        }

        return $rules;
    }
}

if (!function_exists('asana_automator_bootstrap_mapping_rules_for_project')) {
    function asana_automator_bootstrap_mapping_rules_for_project(string $project_gid, string $token): array {
        $fields = asana_automator_bootstrap_fetch_project_fields($project_gid, $token);
        if (empty($fields)) {
            return [
                'ok' => false,
                'message' => 'No custom fields found for this project',
                'rules' => [],
                'json' => '',
            ];
        }

        $rules = asana_automator_bootstrap_build_rules($fields);
        if (empty($rules)) {
            return [
                'ok' => false,
                'message' => 'Could not infer mapping rules from project custom fields',
                'rules' => [],
                'json' => '',
            ];
        }

        return [
            'ok' => true,
            'message' => '',
            'rules' => $rules,
            'json' => wp_json_encode($rules, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
        ];
    }
}
