import { defineConfig } from 'astro/config'

import mdx from '@astrojs/mdx'
import icon from 'astro-icon'

import expressiveCode from 'astro-expressive-code'
import { rehypeHeadingIds } from '@astrojs/markdown-remark'
import rehypeExternalLinks from 'rehype-external-links'
import rehypePrettyCode from 'rehype-pretty-code'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import remarkEmoji from 'remark-emoji'
import remarkGithubAlerts from 'remark-github-blockquote-alert'
import remarkMath from 'remark-math'
import remarkSectionize from 'remark-sectionize'
import rehypeDocument from 'rehype-document'

import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
import { pluginLineNumbers } from '@expressive-code/plugin-line-numbers'

import tailwindcss from "@tailwindcss/vite";
import Icons from 'unplugin-icons/vite';

import svelte from '@astrojs/svelte';
import { fileURLToPath } from 'url';
import path from 'path';

function rehypeDemoteH1AndStripTitle() {
  return (tree: any) => {
    const walk = (node: any, parent: any | null, indexInParent: number | null) => {
      if (!node) return
      const isElement = node.type === 'element'
      if (isElement) {
        if (node.tagName === 'title') {
          if (parent && Array.isArray(parent.children) && indexInParent !== null && indexInParent > -1) {
            parent.children.splice(indexInParent, 1)
            return
          }
        }
        if (node.tagName === 'h1') {
          node.tagName = 'h2'
        }
      }
      if (Array.isArray(node.children)) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          walk(node.children[i], node, i)
        }
      }
    }
    walk(tree, null, null)
  }
}

export default defineConfig({
  site: 'https://patrick.jaroszew.ski',

  integrations: [expressiveCode({
    themes: ['catppuccin-latte', 'ayu-dark'],
    plugins: [pluginCollapsibleSections(), pluginLineNumbers()],
    useDarkModeMediaQuery: true,
    defaultProps: {
      wrap: true,
      collapseStyle: 'collapsible-auto',
      overridesByLang: {
        'ansi,bat,bash,batch,cmd,console,powershell,ps,ps1,psd1,psm1,sh,shell,shellscript,shellsession,text,zsh':
          {
            showLineNumbers: true,
          },
      },
    },
  }), svelte(), mdx(), icon()],

  vite: {
    plugins: [
      tailwindcss() as any,
      Icons({ compiler: 'svelte' }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(path.dirname(fileURLToPath(import.meta.url)), './src'),
        '$lib': path.resolve(path.dirname(fileURLToPath(import.meta.url)), './src/lib')
      }
    },
    optimizeDeps: {
      exclude: ["satori", "satori-html"],
      include: ["clsx"]
    },
  },

  server: {
    port: 3000,
    host: true,
  },

  devToolbar: {
    enabled: false,
  },

  markdown: {
    syntaxHighlight: false,
    rehypePlugins: [
      rehypeDocument,
      [
        rehypeExternalLinks,
        {
          target: '_blank',
          ariaLabel: 'External link'
        },
      ],
      rehypeDemoteH1AndStripTitle,
      rehypeHeadingIds,
      [
        rehypeAutolinkHeadings,
        {
          behavior: 'append',
          properties: {
            className: ['heading-anchor'],
            ariaLabel: 'Link to this section',
          },
          content: {
            type: 'element',
            tagName: 'svg',
            properties: {
              className: ['anchor-icon'],
              xmlns: 'http://www.w3.org/2000/svg',
              width: '16',
              height: '16',
              viewBox: '0 0 24 24',
              fill: 'none',
              stroke: 'currentColor',
              strokeWidth: '2',
              strokeLinecap: 'round',
              strokeLinejoin: 'round'
            },
            children: [
              {
                type: 'element',
                tagName: 'path',
                properties: {
                  d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71'
                }
              },
              {
                type: 'element',
                tagName: 'path',
                properties: {
                  d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'
                }
              }
            ]
          }
        }
      ],
      [
        rehypePrettyCode,
        {
          theme: {
            light: 'catppuccin-latte',
            dark: 'ayu-dark',
          },
        },
      ],
    ],
    remarkPlugins: [remarkMath, remarkEmoji, remarkSectionize, remarkGithubAlerts],
  },
})