import { resolve, dirname } from 'node:path'

export default defineNuxtConfig({
    app: {
        rootId: 'es-app',
        pageTransition: { name: 'page', mode: 'out-in' },
        // keepalive: {
        //     max: 10, // 最多保持 10 個頁面在記憶體中
        //     include: [], // 需要快取的頁面名稱
        // },
        head: {
            htmlAttrs: {
                lang: 'zh-TW',
            },
            charset: 'utf-8',
            titleTemplate: '%s',
            meta: [
                { name: 'app-version', content: process.env.CUSTOM_VERSION },
                { name: 'theme-color', content: '#000000' },
                { name: 'viewport', content: 'width=device-width, initial-scale=1, user-scalable=no, maximum-scale=1, minimum-scale=1' },
                // { name: 'copyright', content: '財富管理 - 永豐銀行' },
                { property: 'og:type', content: 'website' },
                { property: 'og:url', content: 'https://wm.sinopac.com' },
                { property: 'og:image:width', content: '1200' },
                { property: 'og:image:height', content: '630' },
                { property: 'og:image', content: '/socialshare.jpg' },
                { property: 'twitter:image', content: '/socialshare.jpg' },
                { property: 'twitter:card', content: 'summary_large_image' }
            ],
            link: [
                { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
            ],
            noscript: [
                { children: '<style>text{position:fixed;top:0;left:0;width:100vw;height:100vh;font-size:2rem;background-color:#000;color:#fff;z-index:10000;display:flex;align-items:center;justify-content:center;text-align:center;padding:5rem}</style>' },
                { children: '😓 ' + process.env.APP_NAME + '：Sorry your JavaScript is off or your browser does not support JavaScript 😓' }
            ], 
            script: [
                // Google Tag Manager - 放在 HEAD 執行
                {
                    innerHTML: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-NFZC9B8M');`,
                    type: 'text/javascript'
                },
                // 添加 Schema.org JSON-LD
                {
                    type: 'application/ld+json',
                    innerHTML: JSON.stringify({
                        "@context": "https://schema.org",
                        "@type": "Organization",
                        "name": "永豐銀行",
                        "url": "https://wm.sinopac.com",
                        "logo": "https://wm.sinopac.com/favicon.ico"
                    })
                },
                // { src: 'https://static.line-scdn.net/liff/edge/2/sdk.js'}
            ]
        }
    },

    css: [
        '@/assets/styles/main.scss', // global css
    ],

    vite: {
        define: {
            __VUE_PROD_DEVTOOLS__: false,
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@import "@/assets/styles/mixins/mixin.scss";',
                    api: 'modern-compiler',
                    silenceDeprecations: ['legacy-js-api', 'import', 'global-builtin'],
                    quietDeps: true,
                    logger: {
                        warn: function() {
                            // 關閉所有 Sass 警告
                            return;
                        }
                    }
                },
            },
        },
        resolve:{
            alias: {
                '~': resolve(__dirname, './assets/')
            }
        },
        //! 關閉 nuxt-icons 警告使用
        plugins: [ 
            {
            name: 'vite-plugin-glob-transform',
                transform(code: string, id: string) {
                    if (id.includes('nuxt-icons')) {
                        return {
                            code: code.replace(/as:\s*['"]raw['"]/g, 'query: "?raw", import: "default"'),
                            map: null // 明確指定 sourcemap
                        }
                    }
                    return null
                }
            }
        ],
        server: { // 解決開發時 websocket 問題
            hmr: {
                protocol: 'ws',
                host: 'localhost'
            }
        }
    },

    modules: ['nuxt-icons', 'dayjs-nuxt', 'nuxt-security', ['nuxt-delay-hydration', {
        mode: 'init',
        replayClick: true,
        idleCallbackTimeout: 1000,
        replayClickMaxWait: 1000,
        exclude: [
            /^\/_nuxt\//,
            /^\/api\//,
            /^\/assets\//,
        ]
    }], '@nuxtjs/sitemap'],
    site: { 
        url: 'https://wm.sinopac.com', 
        name: '讓財富替你工作，永豐提供你累積財富的各種可能 - 永豐銀行',
    },
    sitemap: {
        sources: [
            '/api/get_sitemap'
        ],
        defaults: {
            changefreq: 'daily',
            priority: 0.8,
            lastmod: new Date()
        }
    },
    // @ts-ignore
    security: {
        nonce: true,
        headers: {
            crossOriginEmbedderPolicy: 'credentialless',
            crossOriginOpenerPolicy: 'same-origin',
            crossOriginResourcePolicy: 'cross-origin',
            originAgentCluster: '?1',
            referrerPolicy: 'strict-origin-when-cross-origin',
            strictTransportSecurity: {
                maxAge: 31536000,
                includeSubdomains: true
            },
            xContentTypeOptions: 'nosniff',
            xFrameOptions: false, // 使用 CSP frame-ancestors 取代
            xXSSProtection: '1; mode=block',
            contentSecurityPolicy: {
                'img-src': ["'self'", 'data:', 'blob:'],
                'style-src': ["'self'", "'unsafe-inline'"],
                'script-src': ["'self'", "'unsafe-inline'", "'nonce-{{nonce}}'", "https://dmp.sinopac.com", "https://www.googletagmanager.com"],
                'connect-src': ["'self'", 'blob:', 'wss:', 'https:', "https://dmp.sinopac.com", "https://www.google-analytics.com", "https://analytics.google.com"],
                'default-src': ["'self'"],
                'font-src': ["'self'", 'https:', 'data:'],
                'frame-src': ["'self'"],
                'media-src': ["'self'"],
                'manifest-src': ["'self'"],
                'worker-src': ["'self'"],
                // build-time fallback：實際清單於 runtime 由 server/plugins/dynamic-frame-ancestors.ts
                // 依環境（encrypted.json 的 FRAME_ANCESTORS）覆寫。此處保留全環境聯集作為安全預設。
                'frame-ancestors': [
                    "'self'",
                    // 'http://10.11.37.176',
                    // 'http://10.11.66.110',
                    'https://dawho.sinopac.com',
                    'https://dawhosb.sinopac.com',
                    'https://dawhosb8443-sinopac.cdn.hinet.net',
                    // 'https://wm-sit.test',
                    // 'https://wm-uat.test',
                    'https://wm.sinopac.com'
                ]
            },
            permissionsPolicy: {
                camera: [],
                microphone: [],
                geolocation: [],
                fullscreen: [],
                'display-capture': []
            }
        },
        rateLimiter: {
            tokensPerInterval: 2000,
            interval: 'hour'
        },
        corsHandler: {
            // 僅保留各環境共用的 https 來源；內部 http 來源（如 dev 的 localhost）改由
            // server/plugins/dynamic-security-config.ts 依環境（encrypted.json 的 CORS_ORIGIN）
            // 於 runtime 附加，避免將 http 來源寫進原始碼／建置產物而被弱點掃描標記。
            origin: [
                'https://wmap-sit.test',
                'https://wmap-uat.test',
                'https://wmap.sinopac.com',
                'https://dmp.sinopac.com'
            ],
            methods: ['GET', 'HEAD', 'POST'],
            preflight: {
                statusCode: 204
            },
            allowHeaders: ['Content-Type', 'Authorization'],
            credentials: true
        }
    },

    devtools: {
      // enabled: process.env.ENV === 'dev',
      enabled: false,

    //   timeline
    },
    build: {
        analyze: true,
    },
    hooks: {
        'close': async () => {
            const version = process.env.CUSTOM_VERSION
            
            try {
                const fs = await import('fs/promises')
                const filePath = './.output/nitro.json'
                
                // 刪除 public/images 資料夾
                try {
                    await fs.rm('./.output/public/images', { recursive: true, force: true })
                    console.log('\x1b[32m\x1b[1m✓ 成功刪除 public/images 資料夾\x1b[0m')
                } catch (error) {
                    console.log('\x1b[33m\x1b[1m⚠️ 刪除 public/images 資料夾時發生錯誤，可能是資料夾不存在\x1b[0m')
                }
                
                // 讀取現有的 nitro.json
                const existingContent = await fs.readFile(filePath, 'utf-8')
                const nitroConfig = JSON.parse(existingContent)

                // 更新 build-info
                const updatedConfig = {
                    ...nitroConfig,
                    'build-info': {
                        version,
                        env: process.env.ENV
                    }
                }
                
                // 寫入更新後的配置
                await fs.writeFile(
                    filePath,
                    JSON.stringify(updatedConfig, null, 2)
                )

                // 讀取並修改 server/chunks/nitro/nitro.mjs
                const runtimeFilePath = './.output/server/chunks/nitro/nitro.mjs'
                let runtimeContent = await fs.readFile(runtimeFilePath, 'utf-8')

                // 移除 sendRedirect 函數
                runtimeContent = runtimeContent.replace(
                    /function sendRedirect\(([^)]*)\) {[\s\S]*?return send\(event, html, MIMES\.html\);[\s\S]*?}/,
                    ''
                )

                // 移除 return sendRedirect 語句
                runtimeContent = runtimeContent.replace(
                    /return sendRedirect\(event, target, routeRules\.redirect\.statusCode\);/,
                    ''
                )

                // 寫入修改後的 runtime.mjs
                await fs.writeFile(runtimeFilePath, runtimeContent)

            } catch (error) {
                console.error('在寫入 Build info 或修改 runtime.mjs 時產生錯誤:', error)
            }

            // 黃色背景的成功訊息
            console.log('\x1b[43m\x1b[30m ES BUILD 成功，恭喜你！ \x1b[0m')
            console.log('                         .-.')
            console.log('(_______________________()6 `--,')
            console.log('(   __________________   /"""`')
            console.log('//\\                  //\\')
            console.log('"" ""                 "" ""')
        },
          
    },
    nitro: {
        externals: {
            traceExclude: ['@vue/devtools-api'],
        },
        debug: true,
        logLevel: 3,
        minify: true,
        compressPublicAssets: {
            gzip: true,
            brotli: true
        },
        sourceMap: false,
        timing: false,
        storage: {
            data: {
                driver: 'memory'
            }
        },
        routeRules: {
            // '/**': { 
            //     cors: true,
            //     headers: {
            //         'Access-Control-Allow-Methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
            //         'Access-Control-Allow-Origin': '*',
            //         'Access-Control-Allow-Credentials': 'true',
            //         'Access-Control-Allow-Headers': '*',
            //         'Access-Control-Expose-Headers': '*',
            //         'Cache-Control': 'public, max-age=600'
            //     }
            // },
            // '/': {
            //     cache: { 
            //         maxAge: 3600, // 快取 1 小時
            //         swr: true     // 啟用 Stale-While-Revalidate 策略
            //     }
            // },
            // '/fund': {
            //     cache: { 
            //         maxAge: 3600, // 快取 1 小時
            //         swr: true     // 啟用 Stale-While-Revalidate 策略
            //     }
            // },
            '/assets/**': {
                headers: {
                    'cache-control': 'public, max-age=31536000, immutable'
                }
            },
            '/_nuxt/**': {
                headers: {
                    'cache-control': 'public, max-age=31536000, immutable'
                }
            }
        },
        serverAssets: [{
            baseName: 'public',
            dir: 'public'
        }]
    }
})