#!/usr/bin/env python3
# Usage: python3 legalpages.py <site> <plan|apply>
import os, re, sys, shutil, subprocess

BAK = '.bak-legal-20261123'
HOME = os.path.expanduser('~')

FR = {'privacy': 'Politique de confidentialité', 'cg': 'Conditions générales'}
NL = {'privacy': 'Privacybeleid', 'cg': 'Algemene voorwaarden'}
EN = {'privacy': 'Privacy policy', 'cg': 'Terms and conditions'}
LABELS = {'fr': FR, 'nl': NL, 'en': EN}


def desc(lang, kind, name):
    if lang == 'en':
        if kind == 'privacy':
            return "Privacy policy of %s: what data we collect, why, how long we keep it and your rights under the GDPR." % name
        return "Terms and conditions of %s for quote requests and clearance jobs." % name
    if lang == 'fr':
        if kind == 'privacy':
            return "Politique de confidentialité de %s : données collectées, utilisation, conservation et exercice de vos droits (RGPD)." % name
        return "Conditions générales de %s applicables aux demandes de devis et aux interventions." % name
    if kind == 'privacy':
        return "Privacybeleid van %s: welke gegevens we verzamelen, waarvoor, hoe lang en uw rechten (AVG)." % name
    return "Algemene voorwaarden van %s voor offerteaanvragen en opdrachten." % name


# ---------- main content builders ----------
def main_tpl_bootstrap(h1, body):
    # debarrastout / huizen-leegmaken (same theme)
    home = 'Accueil' if h1 in FR.values() else 'Home'
    return ('<section>\n        <div class="gap black-layer opc8 overlap144">\n'
            '            <div class="fixed-bg2" style="background-image: url(assets/images/s2.jpg);"></div>\n'
            '            <div class="container">\n                <div class="pg-tp-wrp">\n'
            '                    <h1 itemprop="headline">%s</h1>\n'
            '                    <ol class="breadcrumb">\n'
            '                        <li class="breadcrumb-item"><a href="/" title="" itemprop="url">%s</a></li>\n'
            '                        <li class="breadcrumb-item active">%s</li>\n'
            '                    </ol>\n                </div>\n            </div>\n        </div>\n    </section>\n'
            '    <section>\n        <div class="gap">\n            <div class="container">\n'
            '                <div class="abt-desc">\n%s\n                </div>\n'
            '            </div>\n        </div>\n    </section>\n\n    ') % (h1, home, h1, body)


def main_nicepage(h1, body):
    return ('\n  <section class="u-clearfix">\n'
            '    <div class="u-clearfix u-sheet" style="min-height:0;padding:40px 0 60px;">\n'
            '      <h1>%s</h1>\n%s\n    </div>\n  </section>\n\n  ') % (h1, body)


def main_charleroi(h1, body):
    return '<h1>%s</h1>\n%s' % (h1, body)


def main_bxl(h1, body):
    return ('<section class="article-hero">\n        <div class="container">\n'
            '            <div class="article-breadcrumb"><a href="index.html">Accueil</a> /\n'
            '                <span>%s</span>\n            </div>\n'
            '            <h1>%s</h1>\n        </div>\n    </section>\n\n'
            '    <section class="article-content">\n        <div class="container">\n'
            '            <div class="article-body">\n%s\n            </div>\n        </div>\n    </section>\n\n    ') % (h1, h1, body)


def main_housse(h1, body):
    return ('<section class="section">\n    <div class="container" style="max-width:860px;">\n'
            '      <h1>%s</h1>\n%s\n    </div>\n  </section>\n\n  ') % (h1, body)


def post_housse(txt):
    # header nav anchors point to the home page; drop the home-page contact-form script (no form here)
    hb = re.search(r'<header class="header">.*?</header>', txt, re.S).group(0)
    nhb = hb.replace('href="#"', 'href="/"').replace('href="#', 'href="/#')
    txt = txt.replace(hb, nhb, 1)
    m = re.search(r'[ 	]*<!-- JavaScript -->\s*<script>.*?</script>\s*', txt, re.S)
    if not m or 'contactForm' not in m.group(0):
        raise Exception('form script not found')
    return txt[:m.start()] + txt[m.end():]


SITES = {
    'housse': dict(dom='house-clearance.be', name='House Clearance Brussels', lang='en', contact='/#contact',
                   pages={'privacy': 'privacy-policy.html', 'cg': 'terms-and-conditions.html'},
                   tpl='index.html', start=r'[ 	]*<!-- Hero Section -->', end=r'<footer', main=main_housse, post=post_housse),
    'debarras1': dict(dom='debarrastout.com', name='Débarras Tout', lang='fr', contact='/contact.php',
                      pages={'privacy': 'politique-confidentialite.php', 'cg': 'conditions-generales.php'},
                      tpl='vide-garage.php', start=r'<section>', end=r"<\?php include 'footer\.php'; \?>",
                      main=main_tpl_bootstrap, htmllang=('<html lang="en">', '<html lang="fr">')),
    'videflamad': dict(dom='huizen-leegmaken.be', name='Huizen Leegmaken', lang='nl', contact='/contact.php',
                       pages={'privacy': 'privacy.php', 'cg': 'algemene-voorwaarden.php'},
                       tpl='lift.php', start=r'<section>', end=r"<\?php include 'footer\.php'; \?>",
                       main=main_tpl_bootstrap, htmllang=('<html lang="en">', '<html lang="nl-BE">')),
    'huisantwerpen': dict(dom='huis-leegmaken-antwerpen.be', name='Huis leegmaken Antwerpen', lang='nl', contact='/#form1',
                          pages={'privacy': 'privacy.html', 'cg': 'algemene-voorwaarden.html'},
                          tpl='Contact.html', start=r'(?<=</header>)', end=r'<footer', main=main_nicepage),
    'antwerpen': dict(dom='inboedel-opruimen-antwerpen.be', name='Inboedel Opruimen Antwerpen', lang='nl', contact='/#form1',
                      pages={'privacy': 'privacy.html', 'cg': 'algemene-voorwaarden.html'},
                      tpl='Contact.html', start=r'(?<=</header>)', end=r'<footer', main=main_nicepage,
                      htmllang=('<html style="font-size: 16px;">', '<html style="font-size: 16px;" lang="nl-BE">')),
    'mons': dict(dom='vide-maison-mons.be', name='Vide Maison Mons', lang='fr', contact='/#carousel_1b0d',
                 pages={'privacy': 'politique-confidentialite.html', 'cg': 'conditions-generales.html'},
                 tpl='Contact.html', start=r'(?<=</header>)', end=r'<footer', main=main_nicepage),
    'charleroi': dict(dom='vide-maison-charleroi.com', name='Vide maison Charleroi', lang='fr', contact='/#contact-rappel',
                      pages={'privacy': 'politique-confidentialite.html', 'cg': 'conditions-generales.html'},
                      tpl='mentions-legales.html', start=r'<h1>', end=r'\s*</div>\s*</div>\s*</section>', main=main_charleroi),
    'videmaisonbruxelles': dict(dom='vide-maisons-bruxelles.be', name='Vide Maisons Bruxelles', lang='fr', contact='/#contact',
                                pages={'privacy': 'politique-confidentialite.html', 'cg': 'conditions-generales.html'},
                                tpl='article-syndrome-diogene.html', start=r'<section class="article-hero">', end=r'<footer',
                                main=main_bxl),
}


def links(cfg, sep, attrs=''):
    lab = LABELS[cfg['lang']]
    p = cfg['pages']
    return '<a href="/%s"%s>%s</a>%s<a href="/%s"%s>%s</a>' % (p['privacy'], attrs, lab['privacy'], sep, p['cg'], attrs, lab['cg'])


def footer_one(txt):
    blocks = re.findall(r'<footer\b.*?</footer>', txt, re.S)
    if len(blocks) != 1:
        raise Exception('footer blocks: %d' % len(blocks))
    return blocks[0]


def mode_new_p(txt, snippet):
    fb = footer_one(txt)
    m = list(re.finditer(r'</div>\s*</footer>', fb))
    if len(m) != 1:
        raise Exception('new_p anchor count %d' % len(m))
    nfb = fb[:m[0].start()] + snippet + '\n    ' + fb[m[0].start():]
    return txt.replace(fb, nfb, 1)


def mode_inline_last_p(txt, snippet):
    fb = footer_one(txt)
    i = fb.rfind('</p>')
    if i < 0:
        raise Exception('no </p> in footer')
    # keep trailing whitespace before </p> after the snippet
    j = i
    while j > 0 and fb[j - 1] in ' \t\r\n':
        j -= 1
    nfb = fb[:j] + snippet + fb[j:]
    return txt.replace(fb, nfb, 1)


def mode_replace(old, new):
    def f(txt, _snip):
        if txt.count(old) != 1:
            raise Exception('replace anchor count %d' % txt.count(old))
        return txt.replace(old, new, 1)
    return f


def footer_plan(site, cfg):
    """list of (file, func, snippet)"""
    L = []
    lang = cfg['lang']
    if site in ('debarras1', 'videflamad'):
        old = 'ALL RIGHTS RESERVED</p>'
        new = 'ALL RIGHTS RESERVED &middot; ' + links(cfg, ' &middot; ', ' title="" itemprop="url"') + '</p>'
        files = ['footer.php', 'footer1.php'] if site == 'debarras1' else ['footer.php']
        for f in files:
            L.append((f, mode_replace(old, new), None))
    elif site == 'huisantwerpen':
        snip = ('<p class="u-small-text u-text u-text-variant" style="margin:10px auto 20px;text-align:center;">'
                + links(cfg, ' - ', ' style="color:inherit;text-decoration:underline;"') + '</p>')
        for f in ['index.html', 'about.php', 'Contact.html', 'About.html', 'Accueil.html', 'blog/blog.html',
                  'blog/post.html'] + ['blog/post-%d.html' % i for i in range(1, 6)]:
            L.append((f, mode_new_p, snip))
    elif site == 'antwerpen':
        inl = ' | ' + links(cfg, ' | ', ' style="color:inherit;"')
        for f in ['index.html', 'about2.php']:
            L.append((f, mode_inline_last_p, inl))
        snip = ('<p class="u-small-text u-text u-text-variant" style="margin:10px auto 20px;text-align:center;">'
                + links(cfg, ' | ', ' style="color:inherit;text-decoration:underline;"') + '</p>')
        for f in ['Contact.html', 'About.html', 'Accueil.html']:
            L.append((f, mode_new_p, snip))
    elif site == 'mons':
        snip = ('<p class="u-text" style="margin:10px auto 20px;text-align:center;font-size:0.875rem;">'
                + links(cfg, ' - ', ' style="color:inherit;text-decoration:underline;"') + '</p>')
        snip_h = '<p class="footer-copyright">' + links(cfg, ' - ') + '</p>'
        for f in ['index.html', 'charleroi.html', 'la-louviere.html', 'saint-ghislain.html', 'Soignies.html',
                  'Tournai.html', 'Binche.html', 'Fleurus.html', 'Braine-le-Comte.html', 'mouscron.html', 'Ath.html',
                  'colfontaine.html', 'Contact.html', 'À-propos-de.html']:
            L.append((f, mode_new_p, snip))
        L.append(('hainaut.html', mode_new_p, snip_h))
    elif site == 'charleroi':
        old = 'Mentions légales</a></p>'
        new = 'Mentions légales</a> · ' + links(cfg, ' · ', ' class="text-white-50"') + '</p>'
        files = ['index.html'] + sorted(f for f in os.listdir('.') if re.match(r'^vide-maison-[a-z-]+\.html$', f))
        for f in files:
            L.append((f, mode_replace(old, new), None))
    elif site == 'housse':
        L.append(('index.html', mode_inline_last_p, ' | ' + links(cfg, ' | ', ' style="color:inherit;"')))
        L.append(('about.php', mode_inline_last_p, ' | ' + links(cfg, ' | ', ' style="color:inherit;"')))
        snip = ('<p style="margin:10px auto 20px;text-align:center;font-size:0.875rem;">'
                + links(cfg, ' | ', ' style="color:inherit;text-decoration:underline;"') + '</p>')
        for f in ['Accueil.html', 'Contact.html', 'À-propos-de.html']:
            L.append((f, mode_new_p, snip))
    elif site == 'videmaisonbruxelles':
        old = ('<a href="#"\n            onclick="document.getElementById(\'privacyModal\').style.display=\'flex\';return false;">Politique de\n'
               '            confidentialité</a>')
        new = links(cfg, ' | ')
        L.append(('index.html', mode_replace(old, new), None))
        inl = ' | ' + links(cfg, ' | ')
        for f in ['blog.html'] + sorted(f for f in os.listdir('.') if re.match(r'^article-[a-z-]+\.html$', f)):
            L.append((f, mode_inline_last_p, inl))
    return L


def build_page(cfg, kind):
    lab = LABELS[cfg['lang']][kind]
    body = subprocess.check_output(['python3', os.path.join(HOME, 'legalgen.py'), cfg['dom'], cfg['lang'], kind,
                                    cfg['contact']]).decode('utf-8').strip()
    if '0459.006.473' not in body:
        raise Exception('BCE missing in generated content')
    txt = open(cfg['tpl'], encoding='utf-8', newline='').read()
    title = '%s | %s' % (lab, cfg['name'])
    d = desc(cfg['lang'], kind, cfg['name'])
    url = 'https://%s/%s' % (cfg['dom'], cfg['pages'][kind])
    # content region
    ms = re.search(cfg['start'], txt)
    me = re.search(cfg['end'], txt[ms.end():] if ms else '')
    if not ms or not me:
        raise Exception('content markers not found')
    a = ms.start()
    b = ms.end() + me.start()
    txt = txt[:a] + cfg['main'](lab, body) + txt[b:]
    # head
    txt, n = re.subn(r'<title>.*?</title>', '<title>%s</title>' % title, txt, count=1, flags=re.S)
    if n != 1:
        raise Exception('no title')
    txt = re.sub(r'[ \t]*<meta name="robots"[^>]*>\s*\n?', '', txt)
    txt = re.sub(r'[ \t]*<link rel="canonical"[^>]*>\s*\n?', '', txt)
    txt = re.sub(r'[ \t]*<meta name="description"[^>]*>\s*\n?', '', txt, flags=re.S)
    txt = re.sub(r'(<meta property="og:title"\s+content=")[^"]*(")', lambda m: m.group(1) + title + m.group(2), txt)
    txt = re.sub(r'(<meta property="og:description"\s+content=")[^"]*(")', lambda m: m.group(1) + d + m.group(2), txt)
    head_add = ('\n    <meta name="description" content="%s">\n    <meta name="robots" content="noindex, follow">\n'
                '    <link rel="canonical" href="%s">') % (d, url)
    txt = re.sub(r'(<title>.*?</title>)', lambda m: m.group(1) + head_add, txt, count=1, flags=re.S)
    if 'post' in cfg:
        txt = cfg['post'](txt)
    if 'htmllang' in cfg:
        o, nw = cfg['htmllang']
        if txt.count(o) != 1:
            raise Exception('html lang anchor')
        txt = txt.replace(o, nw, 1)
    return txt


def main():
    site, action = sys.argv[1], sys.argv[2]
    cfg = SITES[site]
    os.chdir(os.path.join(HOME, site))
    # new pages
    new = {}
    for kind in ('privacy', 'cg'):
        fn = cfg['pages'][kind]
        if os.path.exists(fn):
            raise Exception('exists: ' + fn)
        new[fn] = build_page(cfg, kind)
    # footer changes
    changes = []
    for f, func, snip in footer_plan(site, cfg):
        old = open(f, encoding='utf-8', newline='').read()
        nt = func(old, snip)
        if nt == old:
            raise Exception('no change ' + f)
        if os.path.exists(f + BAK):
            raise Exception('backup exists ' + f)
        changes.append((f, old, nt))
    if action == 'plan':
        for fn, t in new.items():
            out = '/tmp/legalprev-%s-%s' % (site, fn.replace('/', '_'))
            open(out, 'w', encoding='utf-8', newline='').write(t)
            print('NEW', fn, len(t), '->', out)
        import difflib
        for f, o, n in changes:
            dl = [l for l in difflib.unified_diff(o.splitlines(), n.splitlines(), lineterm='', n=0) if l[:1] in '+-' and l[:3] not in ('+++', '---')]
            print('MOD', f, '| ' + ' || '.join(x[:400] for x in dl))
        return
    # apply
    for f, o, n in changes:
        shutil.copy2(f, f + BAK)
    for f, o, n in changes:
        with open(f, 'w', encoding='utf-8', newline='') as fh:
            fh.write(n)
        print('MOD', f)
    for fn, t in new.items():
        with open(fn, 'w', encoding='utf-8', newline='') as fh:
            fh.write(t)
        shutil.copymode(cfg['tpl'], fn)
        print('NEW', fn)
    # php lint
    bad = False
    for f in [c[0] for c in changes] + list(new):
        if f.endswith('.php'):
            r = subprocess.run(['php', '-l', f], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            ok = r.returncode == 0
            print('LINT', f, 'OK' if ok else 'FAIL ' + r.stdout.decode()[:300])
            bad = bad or not ok
    if bad:
        print('LINT FAILED -> restoring')
        for f, o, n in changes:
            shutil.copy2(f + BAK, f)
        for fn in new:
            os.remove(fn)


if __name__ == '__main__':
    main()
