import { json } from '@sveltejs/kit';
import { api } from '$lib/ae_api/api';
import * as public_env from '$env/static/public';
import type { RequestHandler } from './$types';

/**
 * Modern Dynamic Web Manifest Generator
 * Reference: https://web.dev/articles/add-manifest
 */
export const GET: RequestHandler = async ({ url, fetch }) => {
    const fqdn = url.host;

    const protocol = public_env.PUBLIC_AE_API_PROTOCOL || 'https';
    const server = public_env.PUBLIC_AE_API_SERVER || 'api.oneskyit.com';
    const port = public_env.PUBLIC_AE_API_PORT || '443';
    const path = public_env.PUBLIC_AE_API_PATH || '';
    const api_base_url = `${protocol}://${server}${port === '443' || port === '80' ? '' : ':' + port}${path}`;

    const api_cfg = {
        base_url: api_base_url,
        headers: {
            // Bootstrap key: limited-permission key for unauthenticated domain lookups (least privilege)
            'x-aether-api-key': public_env.PUBLIC_AE_BOOTSTRAP_KEY,
            'x-no-account-id': public_env.PUBLIC_AE_NO_ACCOUNT_ID
        },
        fetch
    };

    let site_domain = null;
    try {
        // Use structured filter for exact matching
        const search_query = {
            and: [{ field: 'fqdn', op: 'eq', value: fqdn }]
        };

        const result_li = await api.search_ae_obj({
            api_cfg,
            obj_type: 'site_domain',
            search_query,
            view: 'base',
            limit: 1,
            log_lvl: 0
        });

        if (result_li && result_li.length > 0) {
            site_domain = result_li[0];
        }
    } catch (e) {
        console.error(`PWA Manifest: Lookup failed for domain ${fqdn}`);
    }

    // Default branding
    const branding_name =
        site_domain?.account_name || site_domain?.name || 'Aether';
    const name = `One Sky IT - ${branding_name} Aether PWA`;
    const short_name = `${site_domain?.account_code || site_domain?.code || 'Aether'} PWA`;
    const background_color =
        site_domain?.cfg_json?.pwa_background_color || 'hsl(220, 65%, 31%)';
    const theme_color = '#3a5997';

    const manifest = {
        id: `ae-pwa-${fqdn}`, // Unique ID for this installation
        name: name,
        short_name: short_name,
        description: `The ${name} platform for unified event and documentation management.`,
        start_url: '/',
        scope: '/',
        display: 'fullscreen',
        background_color: background_color,
        theme_color: theme_color,
        orientation: 'any',
        categories: ['business', 'productivity', 'utilities'],
        icons: [
            // Standard Icons (Small/Med)
            {
                sizes: '24x24',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_24px.png',
                type: 'image/png'
            },
            {
                sizes: '48x48',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_48px.png',
                type: 'image/png'
            },
            {
                sizes: '96x96',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_96px.png',
                type: 'image/png'
            },
            {
                sizes: '144x144',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_144px.png',
                type: 'image/png'
            },
            {
                sizes: '180x180',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_180px.png',
                type: 'image/png'
            },
            // High-res Maskable Icons (WebP preferred for efficiency)
            {
                sizes: '192x192',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_192px.webp',
                type: 'image/webp',
                purpose: 'any maskable'
            },
            {
                sizes: '192x192',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_192px.png',
                type: 'image/png',
                purpose: 'any maskable'
            },
            {
                sizes: '512x512',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_512px.webp',
                type: 'image/webp',
                purpose: 'any maskable'
            },
            {
                sizes: '512x512',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_512px.png',
                type: 'image/png',
                purpose: 'any maskable'
            },
            {
                sizes: '1024x1024',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_1024px.webp',
                type: 'image/webp',
                purpose: 'any maskable'
            },
            {
                sizes: '1024x1024',
                src: 'https://static.oneskyit.com/images/OSIT_logo_2022_1024px.png',
                type: 'image/png',
                purpose: 'any maskable'
            }
        ],
        // App Shortcuts (Long-press icon features)
        shortcuts: [
            {
                name: 'Journals',
                short_name: 'Journals',
                description: 'View and manage journal entries',
                url: '/journals',
                icons: [
                    {
                        src: 'https://static.oneskyit.com/images/OSIT_logo_2022_192px.png',
                        sizes: '192x192'
                    }
                ]
            },
            {
                name: 'Events',
                short_name: 'Events',
                description: 'Access active event management',
                url: '/events',
                icons: [
                    {
                        src: 'https://static.oneskyit.com/images/OSIT_logo_2022_192px.png',
                        sizes: '192x192'
                    }
                ]
            },
            {
                name: 'Testing',
                short_name: 'Testing',
                description: 'System diagnostic dashboard',
                url: '/testing',
                icons: [
                    {
                        src: 'https://static.oneskyit.com/images/OSIT_logo_2022_192px.png',
                        sizes: '192x192'
                    }
                ]
            }
        ],
        testing: 'One Sky IT'
    };

    return json(manifest, {
        headers: {
            'Content-Type': 'application/manifest+json',
            'Cache-Control': 'public, max-age=3600'
        }
    });
};
