"""Second pass: the Exhibitions page itself is empty, so find where its
content actually lives - a page builder's meta, a custom post type, or
images attached to the page."""

import os
import re

import pymysql

WP = "/home/abmtgrou/tupyfittings.com"
OUT = "/home/abmtgrou/en.tupyfittings.com/wp-exhibitions"
cfg = open(os.path.join(WP, "wp-config.php"), "r", errors="replace").read()

def const(n):
    m = re.search(r"define\(\s*['\"]" + n + r"['\"]\s*,\s*['\"](.*?)['\"]\s*\)", cfg, re.S)
    return m.group(1) if m else None

p = "VEPSg_"
m = re.search(r"\$table_prefix\s*=\s*['\"]([^'\"]+)", cfg)
if m:
    p = 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")
r = []
with conn.cursor() as c:
    c.execute("SELECT meta_key, LENGTH(meta_value) FROM %spostmeta WHERE post_id=14" % p)
    r.append("=== all meta on page 14 ===")
    for k, n in c.fetchall():
        r.append("  %s  (%s bytes)" % (k, n))

    c.execute("SELECT post_type, post_status, COUNT(*) FROM %sposts GROUP BY post_type, post_status ORDER BY 3 DESC" % p)
    r.append("")
    r.append("=== post types ===")
    for t, s, n in c.fetchall():
        r.append("  %-24s %-10s %s" % (t, s, n))

    c.execute("SELECT ID, post_title, guid FROM %sposts WHERE post_parent=14 AND post_type='attachment'" % p)
    at = c.fetchall()
    r.append("")
    r.append("=== attachments with parent 14: %d ===" % len(at))
    for a in at:
        r.append("  %s  %s  %s" % (a[0], a[1], a[2]))

    # anything anywhere mentioning exhibition
    c.execute("SELECT ID, post_type, post_status, post_title FROM %sposts "
              "WHERE post_title LIKE %%s OR post_name LIKE %%s OR post_content LIKE %%s LIMIT 40" % p,
              ("%exhib%", "%exhib%", "%exhib%"))
    hits = c.fetchall()
    r.append("")
    r.append("=== rows mentioning 'exhib': %d ===" % len(hits))
    for h in hits:
        r.append("  id=%s type=%s status=%s title=%r" % h)

    # uploads folder listing for likely exhibition images
    r.append("")
    r.append("=== uploads folders ===")
    up = os.path.join(WP, "wp-content", "uploads")
    if os.path.isdir(up):
        for y in sorted(os.listdir(up))[:20]:
            r.append("  %s" % y)
conn.close()

out = "\n".join(r)
open(os.path.join(OUT, "report2.txt"), "w").write(out + "\n")
print(out[:2500])