#!/usr/bin/env python3
"""Exports the marketing website's content and design from the Dart server
(server/lib/website*.dart) to resources/dinepad/website.json for the PHP
port (App\\Dine\\Mods\\Website). Run it again after the website changes:

    python3 laravel_server/tools/export_website.py

Needs the Dart SDK (the same one that builds the Flutter apps)."""
import json, os, re, subprocess, sys, tempfile, shutil

here = os.path.dirname(os.path.abspath(__file__))
root = os.path.abspath(os.path.join(here, '..', '..'))
lib = os.path.join(root, 'server', 'lib')
src = open(os.path.join(lib, 'website.dart'), encoding='utf-8').read()

# The private constants at the end of website.dart: copied as they are,
# renamed to public, into a throwaway Dart file next to the content files.
parts = []
for name in ['_waSvg', '_icons', '_css', '_js', '_arText', '_cssJa', '_cssRtl']:
    m = re.search(r'^const ' + re.escape(name) + r'\b', src, re.M)
    if not m:
        sys.exit(f'{name} not found in website.dart')
    start = m.start()
    # Up to the next top-level declaration (or the end of the file).
    nxt = re.search(r'^(const |String |class |///|Website\?)', src[m.end():], re.M)
    end = m.end() + nxt.start() if nxt else len(src)
    parts.append(src[start:end].rstrip().replace('const ' + name, 'const x' + name[1:], 1))

tmp = tempfile.mkdtemp()
try:
    for f in ['website_content.dart', 'website_content_ar.dart', 'website_i18n.dart']:
        shutil.copy(os.path.join(lib, f), tmp)
    names = ['siteIcons', 'defaultGeneral', 'defaultHome', 'defaultStats', 'defaultWhy', 'defaultSteps', 'defaultGallery', 'defaultFeatures',
             'defaultSolutions', 'defaultCities', 'defaultIntegrations', 'defaultHardware', 'defaultFaqs', 'defaultPages', 'defaultLegal', 'defaultPosts', 'defaultShop', 'defaultCountries',
             'arHome', 'arStats', 'arWhy', 'arSteps', 'arGallery', 'arFeatures', 'arSolutions', 'arCities', 'arIntegrations', 'arHardware', 'arFaqs',
             'arPages', 'arLegal', 'arPosts', 'arShop', 'siteText']
    main = ("import 'dart:convert';\nimport 'dart:io';\nimport 'website_content.dart';\nimport 'website_content_ar.dart';\nimport 'website_i18n.dart';\n\n" + '\n\n'.join(parts) +
            "\n\nvoid main() {\n  stdout.write(jsonEncode({\n" +
            ''.join(f"    '{n}': {n},\n" for n in names) +
            "    'waSvg': xwaSvg, 'icons': xicons, 'css': xcss, 'js': xjs, 'arText': xarText, 'cssJa': xcssJa, 'cssRtl': xcssRtl,\n  }));\n}\n")
    open(os.path.join(tmp, 'export.dart'), 'w', encoding='utf-8').write(main)
    out = subprocess.run(['dart', 'run', os.path.join(tmp, 'export.dart')], capture_output=True, text=True, encoding='utf-8')
    if out.returncode != 0:
        sys.exit(out.stderr or out.stdout)
    data = json.loads(out.stdout)
finally:
    shutil.rmtree(tmp)

dest = os.path.join(root, 'laravel_server', 'resources', 'dinepad')
os.makedirs(dest, exist_ok=True)
with open(os.path.join(dest, 'website.json'), 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, separators=(',', ':'))
print(f"website.json: {len(data['defaultFeatures'])} feature pages, {len(data['arText'])} Arabic texts")
