#!/usr/bin/env python3
# Script pour modifier _document.tsx et charger team-block-script.js en premier

import sys

doc_path = "radar-app/src/pages/_document.tsx"

try:
    with open(doc_path, "r") as f:
        content = f.read()

    # Ajouter l'import de Script si pas present
    if "import Script from 'next/script'" not in content and 'import Script from "next/script"' not in content:
        content = content.replace(
            'import { Head, Html, Main, NextScript } from "next/document";',
            'import { Head, Html, Main, NextScript } from "next/document";\nimport Script from "next/script";'
        )

    # Ajouter le script dans <Head> avec strategy="beforeInteractive"
    if "team-block-script.js" not in content:
        # Trouver la fin de <Head /> et la remplacer par un <Head> avec contenu
        if "<Head />" in content:
            content = content.replace(
                "<Head />",
                '<Head>\n          <Script src="/team-block-script.js" strategy="beforeInteractive" />\n        </Head>'
            )
        elif "<Head>" in content and "</Head>" in content:
            # Ajouter avant </Head>
            content = content.replace(
                "</Head>",
                '  <Script src="/team-block-script.js" strategy="beforeInteractive" />\n        </Head>'
            )

    with open(doc_path, "w") as f:
        f.write(content)

    print("_document.tsx modifie pour charger team-block-script.js en premier")
    sys.exit(0)
except Exception as e:
    print(f"Erreur: {e}")
    sys.exit(1)

