"""Pull the Exhibitions page out of the old WordPress database.

phpMyAdmin is throwing an auth error for its temporary session user, so this
reads WordPress's own wp-config.php for the connection details and queries
the database directly. The credentials are used inside this script and are
never printed - only the page content is written out.

The old site was built with Elementor, so the real content usually lives in
the _elementor_data postmeta rather than post_content. Both are dumped.
"""

import json
import os
import re

import pymysql

WP = "/home/abmtgrou/tupyfittings.com"
OUT = "/home/abmtgrou/en.tupyfittings.com/wp-exhibitions"
if not os.path.isdir(OUT):
    os.makedirs(OUT)

cfg = open(os.path.join(WP, "wp-config.php"), "r", errors="replace").read()

def const(name):
    m = re.search(r"define\(\s*['\"]" + name + r"['\"]\s*,\s*['\"](.*?)['\"]\s*\)", cfg, re.S)
    return m.group(1) if m else None

prefix = "wp_"
m = re.search(r"\$table_prefix\s*=\s*['\"]([^'\"]+)", cfg)
if m:
    prefix = m.group(1)

conn = pymysql.connect(
    host=const("DB_HOST") or "localhost",
    user=const("DB_USER"),
    password=const("DB_PASSWORD"),
    database=const("DB_NAME"),
    charset="utf8mb4",
)

report = ["table prefix: %s" % prefix]
with conn.cursor() as cur:
    cur.execute(
        "SELECT ID, post_title, post_name, post_status FROM %sposts "
        "WHERE post_type='page' ORDER BY ID" % prefix)
    pages = cur.fetchall()
    report.append("pages found: %d" % len(pages))
    for p in pages:
        report.append("  id=%s  status=%s  slug=%s  title=%s" % (p[0], p[3], p[2], p[1]))

    target = None
    for p in pages:
        blob = ("%s %s" % (p[1] or "", p[2] or "")).lower()
        if "exhib" in blob or "namayesh" in blob:
            target = p
            break
    if target is None:
        for p in pages:
            if str(p[0]) == "14":
                target = p
                break

    if target:
        pid = target[0]
        report.append("")
        report.append("TARGET: id=%s title=%r slug=%r status=%s" % (pid, target[1], target[2], target[3]))
        cur.execute("SELECT post_content FROM %sposts WHERE ID=%%s" % prefix, (pid,))
        content = cur.fetchone()[0] or ""
        open(os.path.join(OUT, "post_content.html"), "w").write(content)
        report.append("post_content: %d chars" % len(content))

        cur.execute(
            "SELECT meta_key, meta_value FROM %spostmeta WHERE post_id=%%s "
            "AND meta_key IN ('_elementor_data','_wp_page_template','_elementor_edit_mode')" % prefix,
            (pid,))
        for k, v in cur.fetchall():
            v = v or ""
            open(os.path.join(OUT, k.strip("_") + ".txt"), "w").write(v)
            report.append("%s: %d chars" % (k, len(v)))
            if k == "_elementor_data":
                try:
                    urls = sorted(set(re.findall(r"https?://[^\"\\\\ ]+\.(?:jpe?g|png|webp|gif|svg)", v)))
                    open(os.path.join(OUT, "image_urls.txt"), "w").write("\n".join(urls))
                    report.append("image urls in elementor data: %d" % len(urls))
                except Exception as e:
                    report.append("url scan failed: %r" % e)
conn.close()

out = "\n".join(report)
open(os.path.join(OUT, "report.txt"), "w").write(out + "\n")
print(out[:3000])