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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
"""
Export stories from SQLite to standalone HTML files.

Usage:
  1. Export a single story:
       python export_story.py <STORY_ID>
       Example: python convert_SQLITE_to_HTML.bashpy 1974707

  2. Export ALL stories in the database:
       python convert_SQLITE_to_HTML.bashpy --all

  3. Export only stories modified in the current or previous month:
       python convert_SQLITE_to_HTML.bashpy --recent

All exported files are saved in the 'storyhtml/' folder.

Changes applied to every exported file vs. live reader.html:
  - The story JSON is embedded directly in a <script id="embedded-story-data"> tag
    so the file works offline / without the local Flask server.
  - Author links are rewritten from the in-app view
      reader.html#author=<id>  (with onclick=fetchAuthorStories)
    to the original Writing.com profile URL:
      https://www.writing.com/main/view_item/action/show_chapters/user_id/<id>
  - The "Load Story" modal (#initial-load-container) is removed because the
    story loads directly from the embedded JSON.
"""

import sqlite3
import json
import os
import re
import argparse
import time
import zipfile
from datetime import datetime, timedelta

DB_PATH = "story-database.sqlite"
READER_HTML_PATH = "reader.html"
OUTPUT_FILE = "stories-database.zip"

# ── Tag inserted into reader.html to hold the embedded JSON.
# The export_story() regex searches for this exact id.
EMBEDDED_TAG_ID = "embedded-story-data"

# Placeholder tag written at the end of <body> in reader.html so the regex
# always finds it even if no story has been exported yet.
EMBEDDED_TAG_PLACEHOLDER = f'<script id="{EMBEDDED_TAG_ID}" type="application/json"></script>'


def get_db_connection():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def parse_date(date_str):
    """Parse MM-DD-YYYY → datetime, return None on failure."""
    if not date_str:
        return None
    date_str = date_str.strip()
    try:
        return datetime.strptime(date_str, "%m-%d-%Y")
    except Exception:
        return None


def parse_date_to_timestamp(date_str):
    dt = parse_date(date_str)
    return int(dt.timestamp()) if dt else 0


def resolve_public_story_id(story_row):
    """Prefer the canonical Writing.com item_id over internal/archive-only ids."""
    for key in ("url", "url_backup", "extra_url"):
        value = story_row[key] if key in story_row.keys() else ""
        if not value:
            continue
        match = re.search(r'item_id/(\d+)', value)
        if match:
            return match.group(1)

    base_id = str(story_row["base_id"])
    leading_digits = re.match(r'^(\d+)', base_id)
    return leading_digits.group(1) if leading_digits else base_id


def get_story_data(base_id, conn=None):
    """Fetch story + chapters from SQLite and return the JSON-ready dict."""
    close_conn = False
    if conn is None:
        conn = get_db_connection()
        close_conn = True

    story = conn.execute(
        "SELECT * FROM stories WHERE base_id = ?", (base_id,)
    ).fetchone()

    if not story:
        if close_conn:
            conn.close()
        print(f"  [SKIP] Story {base_id} not found in database.")
        return None

    chapters_raw = conn.execute(
        "SELECT * FROM chapters WHERE base_id = ?", (base_id,)
    ).fetchall()
    if close_conn:
        conn.close()

    public_story_id = resolve_public_story_id(story)

    story_data = {
        "info": {
            "id": public_story_id,
            "pretty_title": story["title"],
            "description": story["synopsis"],
            "author_name": (
                story["author_name"]
                if "author_name" in story.keys()
                else story["authorcutename"]
            ),
            "author_id": (
                story["author_raw_name"]
                if "author_raw_name" in story.keys()
                else story["authorid"]
            ),
            "created": parse_date_to_timestamp(story["date"]),
            "source_url": story["url"] if "url" in story.keys() else "",
            "image_url": story["image_url"] if "image_url" in story.keys() else "",
        },
        "chapters": {},
    }

    for c in chapters_raw:
        full_map_id = c["map_id"]
        parts = full_map_id.split("-", 1)
        suffix = parts[1] if len(parts) > 1 else full_map_id

        choices_list = []
        if c["choices"]:
            for choice_str in c["choices"].split("||||"):
                cleaned = re.sub(r"^\d+\.\s*", "", choice_str.strip())
                if cleaned:
                    choices_list.append(cleaned)

        html_content = c["chapter_content"]
        if html_content and html_content.strip().startswith("{"):
            try:
                # Try to parse as JSON to extract actual content if it's wrapped or encoded
                curr = html_content
                # Attempt up to 2 levels of decoding for double-encoded strings
                for _ in range(2):
                    if not isinstance(curr, str) or not curr.strip().startswith("{"):
                        break
                    parsed = json.loads(curr)
                    if isinstance(parsed, dict):
                        # Writing.com API sometimes returns content in "html" or "content" keys
                        extracted = parsed.get("html") or parsed.get("content") or parsed.get("chapter_content")
                        if extracted is not None:
                            curr = extracted
                        else:
                            break # No known content key
                    elif isinstance(parsed, str):
                        curr = parsed
                    else:
                        break
                html_content = curr
            except Exception:
                pass

        if isinstance(html_content, str):
            html_content = re.sub(r'(?i)<br\s*/?>\s*[\n\r]+', '<br>', html_content)
            html_content = re.sub(r'(?i)[\n\r]+\s*<br\s*/?>', '<br>', html_content)

        story_data["chapters"][suffix] = {
            "id": c["map_id"],
            "title": c["chapter_title"],
            "content": html_content,
            "created": parse_date_to_timestamp(c["date"]),
            "choices": choices_list,
            "author_name": (
                c["author_name"]
                if "author_name" in c.keys()
                else story["authorcutename"]
            ),
            "author_id": (
                c["author_raw_name"]
                if "author_raw_name" in c.keys()
                else story["authorid"]
            ),
        }

    return story_data


# ────────────────────────────────────────────────────────────────────────────
# HTML post-processing helpers
# ────────────────────────────────────────────────────────────────────────────

def rewrite_author_links(html):
    """
    Replace every in-app author link:
      <a href="reader.html#author=<id>" onclick="fetchAuthorStories(...)" ...>NAME</a>
    with a plain Writing.com profile link:
      <a href="https://www.writing.com/main/view_item/action/show_chapters/user_id/<id>"
         title="View author profile on Writing.com">NAME</a>

    Also handles the "author:<id>" href variant and JS template literals.
    """
    # Pattern 1: href="(reader.html)#author=ID" with optional onclick
    html = re.sub(
        r'<a\s+href="(?:reader\.html)?#author=([^"]+)"(?:\s+onclick="fetchAuthorStories\([^)]*\);\s*return false;")?\s+title="([^"]*)">',
        lambda m: (
            f'<a href="https://www.writing.com/main/view_item/action/show_chapters/user_id/{m.group(1)}"'
            f' title="{m.group(2) if m.group(2) else "View author profile on Writing.com"}" target="_blank">'
        ),
        html,
    )

    # Pattern 2: href="author:<id>" (used in story info panel)
    html = re.sub(
        r'href="author:([^"]+)"',
        lambda m: (
            f'href="https://www.writing.com/main/view_item/action/show_chapters/user_id/{m.group(1)}"'
            f' target="_blank"'
        ),
        html,
    )

    # Pattern 3: JS template literals like href="#author=${...}"
    html = re.sub(
        r'href="#author=\${([^}]+)}"',
        r'href="https://www.writing.com/main/view_item/action/show_chapters/user_id/${\1}" target="_blank"',
        html,
    )

    # Update title in JS strings for consistency
    html = html.replace(
        'title="Click to view all stories by this author"',
        'title="View author profile on Writing.com"'
    )

    return html


def remove_initial_load_container(html):
    """
    Remove the entire #initial-load-container <div> block from the HTML.
    The exported file loads the story directly from embedded JSON, so the
    modal is never needed and just adds visual noise on first paint.
    """
    html = re.sub(
        r'\s*<div id="initial-load-container">.*?</div>\s*(?=\n?\s*<script)',
        "\n",
        html,
        flags=re.DOTALL,
    )
    return html


def remove_search_button(html):
    """
    Remove the search button from the header.
    Target: .story-header-sticky > .search-container > a.search-btn
    """
    # Matches the search button by its href ("search.html") or class ("search-btn") 
    # to ensure it is removed from the standalone HTML export.
    pattern = r'<a\s+[^>]*?(?:href="search\.html"|class="search-btn")[^>]*?>.*?</a>'
    return re.sub(pattern, '', html, flags=re.DOTALL)


def rewrite_index_links(html):
    """
    Replace the Library index link:
      <a href="index.html" class="index-btn" title="Back to Library Index">Library</a>
    with the online archive URL:
      https://writingarchive.neocities.org/index
    """
    pattern = r'<a href="index\.html" class="index-btn" title="Back to Library Index">Library</a>'
    replacement = r'<a href="https://writingarchive.neocities.org/index" class="index-btn" title="Back to Library Index">Library</a>'
    return re.sub(pattern, replacement, html)


def inject_embedded_json(html, json_str):
    """
    Find the <script id="embedded-story-data"> placeholder and fill it with
    the story JSON.  If the placeholder is absent (older reader.html without
    it), append it just before </body>.
    """
    pattern = (
        r'(<script\s+id="embedded-story-data"[^>]*>)(.*?)(</script>)'
    )

    escaped_json = json_str.replace("</script>", "<\\/script>")

    if re.search(pattern, html, flags=re.DOTALL):
        def _replace(m):
            return f"{m.group(1)}\n{escaped_json}\n{m.group(3)}"
        return re.sub(pattern, _replace, html, flags=re.DOTALL)
    else:
        # Fallback: inject before </body>
        tag = f'<script id="embedded-story-data" type="application/json">\n{escaped_json}\n</script>\n'
        return html.replace("</body>", tag + "</body>", 1)


# ────────────────────────────────────────────────────────────────────────────

def export_story(base_id, reader_html_content, conn=None, zf=None):
    """Build and save a standalone HTML file for one story."""
    story_data = get_story_data(base_id, conn)
    if not story_data:
        return False

    json_str = json.dumps(story_data, ensure_ascii=False, separators=(",", ":"))

    html = reader_html_content

    # 1. Embed the JSON
    html = inject_embedded_json(html, json_str)

    # 2. Rewrite author links → Writing.com profile URLs
    html = rewrite_author_links(html)

    # 3. Remove the "Load Story" modal
    html = remove_initial_load_container(html)

    # 4. Remove the search button
    html = remove_search_button(html)

    # 5. Rewrite Library index link
    html = rewrite_index_links(html)

    if zf is not None:
        zf.writestr(f"{base_id}.html", html)
    else:
        output_path = os.path.join("stories-database(temp)", f"{base_id}.html")
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(html)
    return True


def main():
    start_time = time.time()
    parser = argparse.ArgumentParser(
        description="Export stories from SQLite to standalone HTML files.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    parser.add_argument("story_id", nargs="?", help="Specific story ID to export.")
    parser.add_argument("--all", action="store_true", help="Export all stories.")
    parser.add_argument(
        "--recent",
        action="store_true",
        help="Export only stories modified in the current or previous calendar month.",
    )
    args = parser.parse_args()

    if not os.path.exists(READER_HTML_PATH):
        print(f"Error: {READER_HTML_PATH} not found. Run this script from the same folder as reader.html.")
        return

    with open(READER_HTML_PATH, "r", encoding="utf-8") as f:
        reader_html_content = f.read()

    # Warn if the embedded-story-data placeholder is missing
    if EMBEDDED_TAG_ID not in reader_html_content:
        print(
            f"[WARNING] reader.html does not contain an element with id='{EMBEDDED_TAG_ID}'.\n"
            "  The JSON will be injected before </body> as a fallback.\n"
            f"  Consider adding: {EMBEDDED_TAG_PLACEHOLDER}\n"
            "  just before </body> in reader.html for cleaner exports."
        )

    conn = get_db_connection()
    stories_to_export = []

    # Default to --all when no arguments are provided (e.g. when the script is clicked/run directly)
    if not (args.story_id or args.recent):
        args.all = True

    if args.all:
        print("No arguments provided or --all specified. Fetching all stories from database...")
        rows = conn.execute("SELECT base_id FROM stories ORDER BY base_id").fetchall()
        stories_to_export = [r["base_id"] for r in rows]

    elif args.recent:
        # Current month + previous month
        now = datetime.now()
        # First day of the previous month
        if now.month == 1:
            cutoff = datetime(now.year - 1, 12, 1)
        else:
            cutoff = datetime(now.year, now.month - 1, 1)

        print(
            f"Fetching stories modified since {cutoff.strftime('%Y-%m-%d')} "
            f"(current month + previous month)..."
        )
        rows = conn.execute("SELECT base_id, last_modified FROM stories").fetchall()
        for r in rows:
            lm = parse_date(r["last_modified"])
            if lm and lm >= cutoff:
                stories_to_export.append(r["base_id"])

    elif args.story_id:
        stories_to_export = [args.story_id]

    total = len(stories_to_export)
    print(f"Found {total} stor{'y' if total == 1 else 'ies'} to export -> {OUTPUT_FILE}")

    success_count = 0
    fail_count = 0
    
    # We append if we're not doing a full export and the file exists
    mode = "w" if args.all or not os.path.exists(OUTPUT_FILE) else "a"
    
    with zipfile.ZipFile(OUTPUT_FILE, mode, compression=zipfile.ZIP_DEFLATED) as zf:
        for i, base_id in enumerate(stories_to_export, 1):
            if i % 50 == 0 or i == 1 or i == total:
                print(f"  [{i}/{total}] {base_id}")
            if export_story(base_id, reader_html_content, conn, zf):
                success_count += 1
            else:
                fail_count += 1

    conn.close()
    print(
        f"\nDone! Exported {success_count}/{total} stories to '{OUTPUT_FILE}'."
        + (f" ({fail_count} failed/skipped)" if fail_count else "")
    )

    elapsed = time.time() - start_time
    duration = str(timedelta(seconds=int(elapsed)))
    print(f"\nTotal time: {duration}")

if __name__ == "__main__":
    main()