"""Export the exhibition posts and copy their images across.

The Exhibitions page in WordPress was an empty Blocksy container - the real
content is seven posts, one per show. This pulls each one's title, date,
body and featured image, and copies the image files into the Django app's
media folder so the new page can use them.
"""

import json
import os
import re
import shutil

import pymysql

WP = "/home/abmtgrou/tupyfittings.com"
APP = "/home/abmtgrou/en.tupyfittings.com"
OUT = os.path.join(APP, "wp-exhibitions")
IMGDIR = os.path.join(APP, "media", "exhibitions")
for d in (OUT, IMGDIR):
    if not os.path.isdir(d):
        os.makedirs(d)

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")
posts = []
report = []
with conn.cursor() as c:
    c.execute("SELECT ID, post_title, post_name, post_date, post_content, post_excerpt "
              "FROM %sposts WHERE post_type='post' AND post_status='publish' "
              "ORDER BY post_date" % p)
    rows = c.fetchall()
    for pid, title, name, date, content, excerpt in rows:
        rec = {"id": pid, "title": title, "slug": name,
               "date": str(date), "excerpt": excerpt or "",
               "content_html": content or "",
               "text": re.sub(r"<[^>]+>", " ", content or ""),
               "image": None}
        rec["text"] = re.sub(r"\s+", " ", rec["text"]).strip()
        c.execute("SELECT meta_value FROM %spostmeta WHERE post_id=%%s AND meta_key='_thumbnail_id'" % p, (pid,))
        t = c.fetchone()
        if t:
            c.execute("SELECT meta_value FROM %spostmeta WHERE post_id=%%s AND meta_key='_wp_attached_file'" % p, (t[0],))
            f = c.fetchone()
            if f:
                src = os.path.join(WP, "wp-content", "uploads", f[0])
                if os.path.exists(src):
                    dst = os.path.join(IMGDIR, os.path.basename(f[0]))
                    shutil.copy2(src, dst)
                    rec["image"] = "exhibitions/" + os.path.basename(f[0])
        # any inline images too
        rec["inline_images"] = []
        for u in re.findall(r'src="([^"]+wp-content/uploads/[^"]+)"', content or ""):
            rel = u.split("wp-content/uploads/", 1)[1]
            src = os.path.join(WP, "wp-content", "uploads", rel)
            if os.path.exists(src):
                dst = os.path.join(IMGDIR, os.path.basename(rel))
                shutil.copy2(src, dst)
                rec["inline_images"].append("exhibitions/" + os.path.basename(rel))
        posts.append(rec)
        report.append("id=%s  %s  %s  img=%s  inline=%d  text=%d chars"
                      % (pid, str(date)[:10], title, rec["image"], len(rec["inline_images"]), len(rec["text"])))
conn.close()

open(os.path.join(OUT, "posts.json"), "w").write(json.dumps(posts, ensure_ascii=False, indent=1))
out = "posts: %d\n%s\nimages copied to: %s\n%s" % (
    len(posts), "\n".join(report), IMGDIR, sorted(os.listdir(IMGDIR)))
open(os.path.join(OUT, "report3.txt"), "w").write(out + "\n")
print(out[:2500])