# SANITISED REFERENCE ONLY - NOT TESTED MIGRATION SOFTWARE
# This historical code illustrates patterns for an AI/developer to inspect and adapt.
# Do not run it unchanged. It can write, move, rename or merge files depending on the example.
# Use independent backups, disposable copies, explicit maps and reviewed small batches.
# Private routing/sample collections were removed; path defaults are unconfigured placeholders.
# This source has NOT been executed, imported or functionally tested in sanitisation.
# Flat status mapping (illustrative unread, not an agreed user schema) still needs adaptation.
# The file is delivered as .py.txt for inspection, not as a runnable tool.
raise SystemExit("REFERENCE ONLY: inspect, adapt and independently test on fictional copies; execution is disabled.")

#!/usr/bin/env python3
import sys
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)
"""
migrate_pdfs.py
---------------
Migrates Logseq-imported PDFs and annotation pages into a clean Obsidian structure.

What it does:
  1. Strips the Logseq timestamp suffix from PDF filenames and moves them to Content/PDFs/
  2. Transforms hls__*.md annotation pages into <CleanName>_Annotations.md in Content/PDFs/
     - Keeps YAML frontmatter, updating file-path and file fields to new paths
     - Strips Logseq-only metadata lines (ls-type::, :LOGBOOK:, CLOCK: blocks)
     - Keeps page numbers inline as *(p.N)*
  3. Updates all references in other vault notes to point to the new filenames

Historical suggestion only: --dry-run is not a safety certification. Review and adapt before any use to preview all changes without writing anything.
"""

import os
import re
import shutil
import argparse
from pathlib import Path

# ── Config ────────────────────────────────────────────────────────────────────

# Default vault path. Override with --vault on the command line.
# When run on Windows, point at CONFIGURE_REVIEWED_COPY_PATH (or wherever the vault lives).
# In a Cowork session, point at CONFIGURE_REVIEWED_COPY_PATH
VAULT = Path('CONFIGURE_REVIEWED_COPY_PATH')
ASSETS = VAULT / "assets"
PAGES = VAULT / "pages"
TARGET = VAULT / "Content" / "PDFs"

# ── Helpers ───────────────────────────────────────────────────────────────────

TIMESTAMP_RE = re.compile(r'_\d{13}_\d+$')

def clean_name(stem: str) -> str:
    """Remove Logseq timestamp suffix and replace underscores/hyphens with spaces."""
    cleaned = TIMESTAMP_RE.sub('', stem)
    # Replace underscores with spaces, but preserve leading/internal hyphens that
    # look intentional (e.g. 2017072801-software-architecture-patterns)
    cleaned = cleaned.replace('_', ' ').strip()
    return cleaned

def clean_pdf_name(stem: str) -> str:
    """Clean name for PDF file (spaces are fine in Obsidian)."""
    return clean_name(stem)

def clean_annotation_name(stem: str) -> str:
    """Clean name for _Annotations.md file."""
    return clean_name(stem) + "_Annotations"

# ── Build mapping tables ──────────────────────────────────────────────────────

def build_mappings(dry_run: bool):
    """
    Returns:
      pdf_map:   {old_pdf_path: new_pdf_path}
      annot_map: {old_hls_path: new_annot_path}
      name_map:  {old_stem (without hls__): clean_stem} for reference rewriting
    """
    pdf_map = {}
    annot_map = {}
    name_map = {}  # old_pdf_stem → new_pdf_stem (without extension)

    # PDFs
    for pdf in sorted(ASSETS.glob("*.pdf")):
        new_stem = clean_pdf_name(pdf.stem)
        new_path = TARGET / (new_stem + ".pdf")
        # Handle collisions
        if new_path in pdf_map.values():
            new_path = TARGET / (new_stem + f"_{pdf.stem[-5:]}.pdf")
        pdf_map[pdf] = new_path
        name_map[pdf.stem] = new_stem

    # hls_ annotation pages
    for hls in sorted(PAGES.glob("hls__*.md")):
        # hls__Foo_Bar_1234567890123_0.md → stem without hls__ prefix
        raw_stem = hls.stem[len("hls__"):]
        new_stem = clean_annotation_name(raw_stem)
        new_path = TARGET / (new_stem + ".md")
        annot_map[hls] = new_path

    return pdf_map, annot_map, name_map

# ── YAML frontmatter transformer ──────────────────────────────────────────────

def transform_frontmatter(content: str, old_pdf_stem: str, new_pdf_name: str) -> str:
    """Update file-path and file fields in YAML frontmatter."""
    # file-path: ../assets/OldName.pdf  →  Content/PDFs/NewName.pdf
    content = re.sub(
        'CONFIGURE_REVIEWED_COPY_PATH',
        rf'\1Content/PDFs/{new_pdf_name}.pdf',
        content
    )
    # file: - ![...](../assets/OldName.pdf)  or  - [...](../assets/OldName.pdf)
    content = re.sub(
        'CONFIGURE_REVIEWED_COPY_PATH',
        rf'\g<1>{new_pdf_name}.pdf\2Content/PDFs/{new_pdf_name}.pdf\3',
        content
    )
    return content

# ── Body transformer ──────────────────────────────────────────────────────────

def transform_body(body: str) -> str:
    """
    Clean Logseq-specific markup from annotation body:
      - Strip ls-type:: annotation lines
      - Convert hl-page:: N into inline *(p.N)* appended to the preceding highlight
      - Strip :LOGBOOK: ... :END: blocks
      - Strip CLOCK: lines
      - Strip the redundant ![File](...pdf) line at top of body
      - Strip LATER / NOW / TODO / DONE task markers
    """
    lines = body.split('\n')
    result = []
    i = 0

    while i < len(lines):
        line = lines[i]
        stripped = line.strip()

        # Skip :LOGBOOK: ... :END: blocks
        if stripped == ':LOGBOOK:':
            while i < len(lines) and lines[i].strip() != ':END:':
                i += 1
            i += 1  # skip :END:
            continue

        # Skip CLOCK: lines
        if re.match(r'\s*CLOCK:', line):
            i += 1
            continue

        # Skip Logseq highlight metadata lines
        if re.match(r'\s*ls-type::', line):
            i += 1
            continue
        if re.match(r'\s*hl-type::', line):
            i += 1
            continue
        if re.match(r'\s*hl-stamp::', line):
            i += 1
            continue

        # Convert hl-page:: N — append *(p.N)* to the last non-empty result line
        m = re.match(r'(\s*)hl-page::\s*(\d+)', line)
        if m:
            page_num = m.group(2)
            # Find last non-empty line in result and append page ref
            for j in range(len(result) - 1, -1, -1):
                if result[j].strip():
                    result[j] = result[j].rstrip() + f' *(p.{page_num})*'
                    break
            i += 1
            continue

        # Strip the redundant ![File](...pdf) or ![Name.pdf](...pdf) lines
        # These appear at the top of the body and duplicate the frontmatter
        if re.match(r'\s*-\s*!\[.*\.pdf\]\(.*\.pdf\)', line):
            i += 1
            continue

        # Strip LATER / NOW task markers (keep the rest of the line)
        line = re.sub(r'^(\s*-\s*)(LATER|NOW|TODO|DONE)\s+', r'\1', line)

        result.append(line)
        i += 1

    # Remove leading blank lines from body
    while result and not result[0].strip():
        result.pop(0)

    return '\n'.join(result)

# ── Transform a single hls_ file ─────────────────────────────────────────────

def transform_hls_file(hls_path: Path, new_pdf_stem: str) -> str:
    """Read an hls_ file and return transformed content for _Annotations.md."""
    content = hls_path.read_text(encoding='utf-8')

    # Split frontmatter from body
    if content.startswith('---'):
        end = content.find('\n---', 3)
        if end != -1:
            frontmatter = content[:end + 4]
            body = content[end + 4:]
        else:
            frontmatter = ''
            body = content
    else:
        frontmatter = ''
        body = content

    # Transform frontmatter paths
    old_stem = hls_path.stem[len("hls__"):]
    frontmatter = transform_frontmatter(frontmatter, old_stem, new_pdf_stem)

    # Transform body
    body = transform_body(body)

    return frontmatter + '\n' + body

# ── Safe recursive glob (skips symlinks/junctions that cause I/O errors) ──────

def safe_rglob(root: Path, pattern: str):
    """Recursively yield files matching pattern, skipping unreadable dirs."""
    try:
        for entry in root.iterdir():
            if entry.is_symlink():
                continue
            if entry.is_dir():
                yield from safe_rglob(entry, pattern)
            elif entry.match(pattern):
                yield entry
    except OSError:
        pass

# ── Reference rewriter ────────────────────────────────────────────────────────

def rewrite_references(vault: Path, pdf_map: dict, annot_map: dict, name_map: dict, dry_run: bool):
    """
    Walk all .md files outside Content/PDFs and update:
      - [[hls__OldStem]] → [[NewCleanName_Annotations]]
      - ![[hls__OldStem#^blockid]] → ![[NewCleanName_Annotations#^blockid]]
      - ../assets/OldName.pdf → Content/PDFs/NewName.pdf
    """
    # Build lookup: old_hls_stem → new_annot_stem
    hls_to_new = {}
    for hls_path, new_annot_path in annot_map.items():
        old_stem = hls_path.stem  # e.g. hls__Foo_1234_0
        new_stem = new_annot_path.stem  # e.g. Foo_Annotations
        hls_to_new[old_stem] = new_stem

    # Build lookup: old_pdf_stem → new_pdf_stem
    pdf_stem_to_new = {}
    for old_pdf, new_pdf in pdf_map.items():
        pdf_stem_to_new[old_pdf.stem] = new_pdf.stem

    changed_files = []

    for md_file in safe_rglob(vault, "*.md"):
        # Skip the files we're creating
        if md_file.parent == TARGET:
            continue
        # Skip the hls_ source files themselves
        if md_file.name.startswith("hls__"):
            continue

        original = md_file.read_text(encoding='utf-8')
        updated = original

        # Rewrite [[hls__...]] and ![[hls__...#^blockid]]
        for old_stem, new_stem in hls_to_new.items():
            updated = re.sub(
                r'(!?\[\[)' + re.escape(old_stem) + r'(#[^\]]+)?(\]\])',
                lambda m, ns=new_stem: m.group(1) + ns + (m.group(2) or '') + m.group(3),
                updated
            )

        # Rewrite ../assets/OldName.pdf links
        for old_pdf_stem, new_pdf_stem in pdf_stem_to_new.items():
            updated = re.sub(
                r'\.\./assets/' + re.escape(old_pdf_stem) + r'\.pdf',
                f'Content/PDFs/{new_pdf_stem}.pdf',
                updated
            )

        if updated != original:
            changed_files.append(md_file)
            if not dry_run:
                md_file.write_text(updated, encoding='utf-8')

    return changed_files

# ── Main ──────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(description="Migrate Logseq PDFs to Obsidian Content/PDFs/")
    parser.add_argument('--dry-run', action='store_true', help="Preview changes without writing")
    parser.add_argument('--vault', default=str(VAULT), help="Path to vault root")
    args = parser.parse_args()

    vault = Path(args.vault)
    assets = vault / "assets"
    pages = vault / "pages"
    target = vault / "Content" / "PDFs"

    dry_run = args.dry_run
    verb = "[DRY RUN]" if dry_run else "[LIVE]"

    print(f"\n{'='*60}")
    print(f"PDF Migration  {verb}")
    print(f"{'='*60}\n")

    if not dry_run:
        target.mkdir(parents=True, exist_ok=True)

    pdf_map, annot_map, name_map = build_mappings(dry_run)

    # ── Step 1: Move PDFs ──────────────────────────────────────────────────
    print(f"── Step 1: Moving {len(pdf_map)} PDFs ──\n")
    for old_pdf, new_pdf in sorted(pdf_map.items(), key=lambda x: x[0].name):
        print(f"  {old_pdf.name}")
        print(f"  → {new_pdf.name}\n")
        if not dry_run:
            shutil.move(str(old_pdf), str(new_pdf))

    # ── Step 2: Transform hls_ → _Annotations.md ──────────────────────────
    print(f"── Step 2: Transforming {len(annot_map)} annotation files ──\n")
    for hls_path, new_annot_path in sorted(annot_map.items(), key=lambda x: x[0].name):
        raw_stem = hls_path.stem[len("hls__"):]
        new_pdf_stem = name_map.get(raw_stem, clean_pdf_name(raw_stem))
        print(f"  {hls_path.name}")
        print(f"  → {new_annot_path.name}\n")
        if not dry_run:
            transformed = transform_hls_file(hls_path, new_pdf_stem)
            new_annot_path.write_text(transformed, encoding='utf-8')
            hls_path.unlink()  # Remove old hls_ file