# 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
"""
Convert Logseq journal files to Obsidian format.

Handles:
- Date reference conversion: [[Jun 10th, 2025]] → [[2025_06_10]]
- Block embed conversion: {{embed ((uuid))}} → ![[filename#^short_id]]
- #+BEGIN_QUOTE / #+END_QUOTE → markdown blockquotes (> )
- #+BEGIN_TIP / NOTE / IMPORTANT / CAUTION / WARNING / EXAMPLE → Obsidian callouts (> [!type])
- Remove collapsed:: true lines
- Extract blocks with properties (input::, event::, etc.) into separate page files
  with YAML frontmatter, leaving a [[wikilink]] in the journal
- Block reference migration (id:: → ^short_id, ((uuid)) → ![[File#^id]])
"""

import re
import sys
import os
import shutil
from pathlib import Path

# Import shared functions from the pages conversion script
sys.path.insert(0, 'CONFIGURE_REVIEWED_COPY_PATH')
from convert_logseq import (
    MONTHS, SKIP_PROPS, RENAME, SCALAR_PROPS,
    parse_date, is_date_property, convert_date_in_wikilink,
    split_multi_values, format_yaml_value, capitalize_type_value,
    shorten_uuid, build_block_id_map,
    sanitize_filename, logseq_name_to_parts, resolve_link_name,
)

# ─── Configuration ──────────────────────────────────────────────────

# Properties that indicate a block should be extracted into its own page
EXTRACTABLE_PROPS = {
    'input', 'instance-of', 'event', 'producer', 'tags', 'link',
    'source', 'status', 'relates-to', 'reference', 'attendees',
    'date-published', 'temp',
    # Dive-related
    'dive-no', 'dive-date', 'location', 'visibility', 'weights',
    'psi-start', 'psi-end', 'water-temperature', 'dive-time',
    'start-psi', 'end-psi', 'dive-master',
    'max-depth', 'buddy',
    # Lesson-related
    'teacher', 'length',
}

# Properties that should stay on the journal page (daily tracking)
JOURNAL_LEVEL_PROPS = {
    'wake-up-time', 'wake-up-energy', 'bed-time', 'meditated',
    'snooze', 'sleep-quality', 'three-words', 'three_words',
    'exercise', 'wrap-up', 'bridges', 'pull-ups', 'push-ups',
    'breathing-exercise',
}

# Properties to skip entirely
JOURNAL_SKIP_PROPS = {'collapsed', 'title', 'filters', 'query-table', 'query-properties'}

# ─── Extracted page folder routing ──────────────────────────────────

# Map input/event types to output folders
CONTENT_TYPES = {
    'articles', 'videos', 'podcasts', 'tweets', 'picture', 'sermon',
    'sermons', 'twitter thread',
}

DIVE_PROPS = {
    'dive-no', 'dive-date', 'dive-time', 'dive-master',
    'start-psi', 'end-psi', 'psi-start', 'psi-end',
    'water-temperature', 'weights', 'visibility',
    'max-depth', 'buddy', 'location',
}


LESSON_PROPS = {'teacher', 'length'}

# Map instance-of values to folder names for outputs
OUTPUT_TYPE_FOLDERS = {
    'poems': 'poems',
    'essays': 'essays',
    'twitter thread': 'twitter-threads',
    'videos': 'videos',
    'email': 'emails',
    'blog posts': 'blog-posts',
    'decisions 📌': 'decisions',
    'decisions': 'decisions',
    'posts': 'posts',
    'linkedin post': 'linkedin',
    'zettel': 'zettel',
    'projects': 'projects',
}

# Status values that indicate a draft
DRAFT_STATUSES = {'drafts', 'draft', 'to/process', 'processing', 'to/review'}

# Content type → subfolder mapping
CONTENT_TYPE_FOLDERS = {
    'articles': 'Articles',
    'videos': 'Videos',
    'podcasts': 'Podcasts',
    'tweets': 'Tweets',
    'twitter': 'Tweets',
    'picture': 'Pictures',
    'cartoon': 'Pictures',
    'comic': 'Pictures',
    'meme': 'Pictures',
    'infographic': 'Pictures',
    'sermon': 'Sermons',
    'sermons': 'Sermons',
    'email': 'Emails',
    'webinars': 'Webinars',
    'courses': 'Courses',
}

# People who are coaches (sessions with event:: [[meeting]] should be reclassified as coaching)
COACHING_PERSONS = set()  # Configure only from a reviewed fictional test mapping.


def classify_extracted_page(properties: list[tuple], title: str = '') -> tuple[str, str]:
    "\n    Determine which folder an extracted page belongs in.\n    Returns: (category_path, subcategory) where category_path is used for folder routing.\n\n    Possible returns:\n    - ('activities/dives', 'dive')\n    - ('activities/lessons', 'lesson')\n    - ('activities/therapy/Example Person B', 'therapy')  — person-specific subdirectory\n    - ('activities/coaching/Example Person C', 'coaching') — person-specific subdirectory\n    - ('outputs/poems', 'output')               — published outputs by type\n    - ('drafts/essays', 'output')               — draft outputs by type\n    - ('content', 'content')                    — consumed content (input::)\n    - ('meetings', 'meeting')\n    - ('uncategorized', 'uncategorized')\n    "
    prop_keys = {k.lower() for k, v in properties}
    prop_dict = {k.lower(): v for k, v in properties}
    title_lower = title.lower()

    # Check for dive properties
    if prop_keys & DIVE_PROPS:
        return 'Activities/Dives', 'dive'

    # Check for lesson properties (teacher::)
    if 'teacher' in prop_keys:
        return 'Activities/Lessons', 'lesson'

    # Check title for therapy/coaching patterns (with person-specific subdirectory)
    # Patterns: "Therapy/Example Person B", "Therapy with Example Person B", "Coaching/Example Person C",
    #           "Had first session today with Therapy/Example Person D"
    tc_match = re.search(
        r'(Therapy|Coaching)(?:/|\s+with\s+)(\w[\w\s]*)',
        title, re.IGNORECASE
    )
    if tc_match:
        category = tc_match.group(1).lower()  # 'therapy' or 'coaching'
        person = tc_match.group(2).strip()
        safe_person = re.sub(r'[<>:"/\\|?*]', '_', person).strip()
        return f'Activities/{category.capitalize()}/{safe_person}', category

    # Note: no fallback for generic "therapy"/"coaching" in title — those are likely
    # articles/content about therapy, not actual sessions. Only the structured
    # [[Therapy/Person]] or [[Coaching with Person]] patterns trigger extraction.

    # Check for meeting/event — but reclassify known coaches
    event_val = prop_dict.get('event', '').strip().lower().strip('[]')
    if event_val and 'meeting' in event_val:
        # Check if title mentions a known coach
        for coach in COACHING_PERSONS:
            if coach in title_lower:
                safe_person = coach.title()  # "Example Person H" → "Example Person H"
                return f'Activities/Coaching/{safe_person}', 'coaching'
        return 'Meetings', 'meeting'

    # Check for outputs (instance-of::) — things the user created
    if 'instance-of' in prop_keys:
        instance_val = prop_dict.get('instance-of', '').strip().lower()
        inner = re.sub(r'\[\[|\]\]', '', instance_val).strip()
        # Determine type folder
        type_folder = OUTPUT_TYPE_FOLDERS.get(inner, inner.replace(' ', '-') if inner else 'misc')
        # Capitalize folder name
        type_folder_cap = type_folder.replace('-', ' ').title().replace(' ', '-')
        # Check status to decide Outputs/ vs Drafts/
        status_val = re.sub(r'\[\[|\]\]', '', prop_dict.get('status', '').strip().lower()).strip()
        if status_val in DRAFT_STATUSES:
            return f'Drafts/{type_folder_cap}', 'output'
        return f'Outputs/{type_folder_cap}', 'output'

    # Check for consumed content (input::) — articles, podcasts, etc.
    if 'input' in prop_keys:
        input_val = re.sub(r'\[\[|\]\]', '', prop_dict.get('input', '').strip().lower()).strip()
        subfolder = CONTENT_TYPE_FOLDERS.get(input_val, '')
        if subfolder:
            return f'Content/{subfolder}', 'content'
        return 'Content', 'content'

    # Blocks with producer:: or link:: are also consumed content
    if 'producer' in prop_keys or 'link' in prop_keys:
        return 'Content', 'content'

    # Blocks with reference:: are curated resource lists
    if 'reference' in prop_keys:
        return 'References', 'reference'

    # If it has an event, it's a meeting-type thing
    if 'event' in prop_keys:
        return 'Meetings', 'meeting'

    return 'Uncategorized', 'uncategorized'


# Categories that get a date prefix (things that happened on a specific date)
DATE_PREFIX_CATEGORIES = {'dive', 'lesson', 'meeting', 'therapy', 'coaching'}


def adjust_title(title: str, subcategory: str, journal_date: str = '') -> str:
    """Adjust extracted page title based on its type."""
    # Dives: append 'Dive' if not already present
    if subcategory == 'dive' and not title.lower().endswith('dive'):
        title = f"{title} Dive"

    # Lessons: clean up namespace formatting
    if subcategory == 'lesson':
        title = title.replace('/', ' ').replace('_', ' ').strip()
        if 'lesson' not in title.lower():
            title = f"{title} Lesson"

    # Therapy/Coaching: extract person and normalize title
    # "Therapy/Example Person B" → "Therapy with Example Person B"
    # "Had first session today with Therapy/Example Person D" → "Therapy with Example Person D"
    if subcategory in ('therapy', 'coaching'):
        tc_match = re.search(
            r'(Therapy|Coaching)(?:/|\s+with\s+)(\w[\w\s]*)',
            title, re.IGNORECASE
        )
        if tc_match:
            kind = tc_match.group(1).capitalize()
            person = tc_match.group(2).strip()
            title = f"{kind} with {person}"

    # Add date prefix for event-type pages
    if subcategory in DATE_PREFIX_CATEGORIES and journal_date:
        return f"{journal_date} - {title}"

    return title


# ─── Date reference conversion ──────────────────────────────────────

def convert_date_refs_in_line(line: str) -> str:
    """
    Convert date wikilinks in body text:
    [[Jun 10th, 2025]] → [[2025_06_10]]
    [[Apr 8th, 2025]] → [[2025_04_08]]
    """
    def replace_date(m):
        inner = m.group(1)
        converted = parse_date(inner)
        if converted:
            return f"[[{converted}]]"
        return m.group(0)

    return re.sub(r'\[\[([A-Z][a-z]+ \d+(?:st|nd|rd|th)?,?\s*\d{4})\]\]', replace_date, line)


# ─── Org-mode block conversion ──────────────────────────────────────

# Logseq org-mode admonition blocks → Obsidian callout types.
# QUOTE maps to a plain markdown blockquote (no [!type] header) to preserve
# the original lightweight behavior. Everything else becomes a typed callout.
ORG_BLOCK_TO_CALLOUT = {
    'QUOTE': None,
    'TIP': 'tip',
    'NOTE': 'note',
    'IMPORTANT': 'important',
    'CAUTION': 'caution',
    'WARNING': 'warning',
    'EXAMPLE': 'example',
}

_BLOCK_TYPES_RE = '|'.join(ORG_BLOCK_TO_CALLOUT.keys())


def convert_org_blocks(lines: list[str]) -> list[str]:
    """
    Convert Logseq org-mode admonition blocks (#+BEGIN_TIP / #+BEGIN_NOTE / etc.)
    to Obsidian callouts. #+BEGIN_QUOTE becomes a plain markdown blockquote.
    Preserves the indentation level of the surrounding outline.
    """
    result = []
    in_block = False
    block_indent = ''
    callout_type: str | None = None
    header_emitted = False

    begin_re = re.compile(
        rf'^(\s*(?:-\s+)?)\#\+BEGIN_({_BLOCK_TYPES_RE})\s*$',
        re.IGNORECASE,
    )
    end_re = re.compile(
        rf'^\s*\#\+END_(?:{_BLOCK_TYPES_RE})\s*$',
        re.IGNORECASE,
    )

    for line in lines:
        stripped = line.rstrip('\n')

        begin_match = begin_re.match(stripped)
        if begin_match:
            in_block = True
            block_indent = begin_match.group(1)
            callout_type = ORG_BLOCK_TO_CALLOUT[begin_match.group(2).upper()]
            header_emitted = False
            if callout_type is not None:
                result.append(f"{block_indent}> [!{callout_type}]\n")
                header_emitted = True
            continue

        if end_re.match(stripped):
            in_block = False
            callout_type = None
            header_emitted = False
            continue

        if in_block:
            content = stripped.lstrip()
            # Strip any leading '>' Logseq sometimes nests inside the block
            # so the output is a single clean blockquote line.
            if content.startswith('>'):
                content = content[1:].lstrip()
            if content:
                result.append(f"{block_indent}> {content}\n")
            else:
                result.append(f"{block_indent}>\n")
        else:
            result.append(line if line.endswith('\n') else line + '\n')

    return result


# Back-compat alias for any external callers.
convert_org_quotes = convert_org_blocks


# ─── Collapsed removal ──────────────────────────────────────────────

def remove_collapsed_lines(lines: list[str]) -> list[str]:
    """Remove all lines that are just 'collapsed:: true'."""
    result = []
    for line in lines:
        stripped = line.strip()
        if stripped == 'collapsed:: true':
            continue
        result.append(line)
    return result


# ─── Block embed conversion ─────────────────────────────────────────

def convert_block_embeds(lines: list[str], block_id_map: dict, uuid_to_short: dict) -> list[str]:
    """
    Convert {{embed ((uuid))}} → ![[filename#^short_id]]
    """
    embed_pattern = re.compile(r'\{\{embed\s+\(\(([a-f0-9-]{36})\)\)\s*\}\}')

    result = []
    for line in lines:
        def replace_embed(m):
            uuid = m.group(1)
            filename = block_id_map.get(uuid)
            short_id = uuid_to_short.get(uuid, shorten_uuid(uuid))
            if filename:
                return f"![[{filename}#^{short_id}]]"
            else:
                return f"((MISSING-EMBED:{uuid}))"

        line = embed_pattern.sub(replace_embed, line)
        result.append(line)
    return result


# ─── Block reference conversion (id:: and ((uuid))) ─────────────────

def convert_block_refs(lines: list[str], block_id_map: dict, uuid_to_short: dict) -> list[str]:
    """Convert id:: lines and ((uuid)) references in journal body."""
    result = []
    id_line_pattern = re.compile(r'^(\s*(?:-\s+)?)id::\s*([a-f0-9-]{36})\s*$')
    ref_pattern = re.compile(r'\(\(([a-f0-9-]{36})\)\)')

    i = 0
    while i < len(lines):
        line = lines[i]
        id_match = id_line_pattern.match(line.rstrip('\n'))
        if id_match:
            prefix = id_match.group(1)
            uuid = id_match.group(2)
            short_id = uuid_to_short.get(uuid, shorten_uuid(uuid))
            if i + 1 < len(lines):
                next_line = lines[i + 1]
                next_stripped = next_line.rstrip('\n')
                if next_stripped.strip():
                    if '- ' in prefix:
                        content = next_stripped.lstrip()
                        result.append(f"{prefix}{content} ^{short_id}\n")
                    else:
                        result.append(next_stripped.rstrip() + f" ^{short_id}\n")
                    i += 2
                    continue
                else:
                    i += 1
                    continue
            else:
                i += 1
                continue

        def replace_ref(m):
            uuid = m.group(1)
            filename = block_id_map.get(uuid)
            short_id = uuid_to_short.get(uuid, shorten_uuid(uuid))
            if filename:
                return f"![[{filename}#^{short_id}]]"
            else:
                return f"((MISSING-REF:{uuid}))"

        line = ref_pattern.sub(replace_ref, line)
        result.append(line)
        i += 1

    return result


# ─── Property block extraction ──────────────────────────────────────

def get_indent_level(line: str) -> int:
    """Count the indent level of a line (tabs count as 1, leading - doesn't count)."""
    stripped = line.replace('\t', '    ')
    spaces = len(stripped) - len(stripped.lstrip())
    return spaces


def get_block_indent(line: str) -> int:
    """Get the raw indent of a line in terms of tab stops."""
    count = 0
    for ch in line:
        if ch == '\t':
            count += 1
        elif ch == ' ':
            count += 0.25  # approximate
        else:
            break
    return int(count)


def extract_title_from_heading(line: str) -> str | None:
    """
    Extract a page title from a heading line.
    E.g. "- ### [[ITSP Services]]" → "ITSP Services"
    E.g. "- ### The False Promise of Stoicism" → "The False Promise of Stoicism"
    E.g. "#### Tim Ferriss's healing journey" → "Tim Ferriss's healing journey"
    """
    # Strip leading outline markers (-, tabs, spaces)
    stripped = line.strip().lstrip('-').strip()

    # Remove markdown heading markers
    heading_match = re.match(r'^#{1,6}\s+(.*)', stripped)
    if heading_match:
        title = heading_match.group(1).strip()
        # For Therapy/Coaching patterns, use only the first wikilink as the title
        # e.g. "[[Therapy/Example Person E]] [[parts work]]" → "Therapy/Example Person E" (not "Therapy/Example Person E parts work")
        tc_wikilink = re.match(r'\[\[((?:Therapy|Coaching)(?:/|[^\]]*with\s+)[^\]]+)\]\]', title, re.IGNORECASE)
        if tc_wikilink:
            return tc_wikilink.group(1).strip()
        # Remove all wikilink brackets: [[foo]] bar [[baz]] → foo bar baz
        title = re.sub(r'\[\[([^\]]+)\]\]', r'\1', title)
        return title.strip()

    # Also handle cases where the first line is just a wikilinked name or contains wikilinks
    if '[[' in stripped:
        # For Therapy/Coaching patterns, use only the first wikilink
        tc_wikilink = re.match(r'\[\[((?:Therapy|Coaching)(?:/|[^\]]*with\s+)[^\]]+)\]\]', stripped, re.IGNORECASE)
        if tc_wikilink:
            return tc_wikilink.group(1).strip()
        title = re.sub(r'\[\[([^\]]+)\]\]', r'\1', stripped)
        return title.strip()

    # Plain text title (for headings without wikilinks or #)
    if stripped and not stripped.startswith('#'):
        return stripped

    return None


def find_extractable_blocks(lines: list[str]) -> list[dict]:
    """
    Find blocks that have properties (input::, event::, etc.) and should be
    extracted into separate pages.

    A block is:
    - A heading line (### Title) or a bullet with [[name]]
    - Followed by property lines (key:: value)
    - Followed by child content (indented deeper)

    Returns list of dicts with:
    - 'title': page title
    - 'start': start line index (the heading)
    - 'end': end line index (exclusive)
    - 'properties': list of (key, value) tuples
    - 'body_start': line index where body content begins
    - 'indent': the base indent level of this block
    """
    blocks = []
    i = 0

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

        # Skip empty lines
        if not stripped:
            i += 1
            continue

        # Look for a heading or bullet that might have properties on next lines
        # Check if the NEXT lines have extractable properties
        props = []
        prop_end = i + 1

        # First, check if this line itself has a property (e.g. "input:: [[sermon]]" on same line as heading)
        # That's handled differently - look at the next lines for properties
        base_indent = get_block_indent(line)

        # Scan ahead for property lines at a slightly deeper or same level
        j = i + 1
        while j < len(lines):
            prop_line = lines[j].strip()
            if not prop_line:
                j += 1
                continue
            prop_match = re.match(r'^([a-zA-Z_-]+)::\s*(.*)', prop_line)
            if prop_match:
                key = prop_match.group(1).strip().lower()
                value = prop_match.group(2).strip().rstrip(',').strip()
                if key not in JOURNAL_SKIP_PROPS and key not in JOURNAL_LEVEL_PROPS:
                    props.append((prop_match.group(1).strip(), value))
                j += 1
            else:
                break
        prop_end = j

        # Check if any properties are extractable
        has_extractable = any(k.lower() in EXTRACTABLE_PROPS for k, v in props)

        # Also detect [[Therapy/X]] or [[Coaching/X]] blocks even without properties
        is_therapy_coaching = False
        if not has_extractable:
            # Check if heading line matches Therapy or Coaching wikilink pattern
            # Patterns: [[Therapy/Example Person B]], [[Coaching/Example Person C]], [[Coaching with Example Person F]]
            tc_match = re.search(
                r'\[\[(Therapy|Coaching)(?:/|\s+with\s+)([^\]]+)\]\]',
                stripped, re.IGNORECASE
            )
            if tc_match:
                # Skip non-person entries like [[Therapy/Questions]]
                person_name = tc_match.group(2).strip()
                THERAPY_NON_PERSONS = {'questions', 'notes', 'todo', 'topics'}
                if person_name.lower() in THERAPY_NON_PERSONS:
                    i += 1
                    continue
                # Only extract if this line is a heading (### or top-level bullet)
                # and has child content (next non-empty line is more indented)
                has_children = False
                for k in range(i + 1, min(i + 5, len(lines))):
                    if lines[k].strip():
                        if get_block_indent(lines[k]) > base_indent:
                            has_children = True
                        break
                if has_children:
                    is_therapy_coaching = True

        if has_extractable or is_therapy_coaching:
            title = extract_title_from_heading(line)
            if not title:
                # Use properties to generate a title
                for k, v in props:
                    if k.lower() == 'input' or k.lower() == 'instance-of':
                        title = v.strip('[]').strip()
                        break
                if not title:
                    i += 1
                    continue

            # Find the end of this block (all children)
            block_end = prop_end
            while block_end < len(lines):
                next_line = lines[block_end]
                if not next_line.strip():
                    # Empty line - check if next non-empty line is still a child
                    lookahead = block_end + 1
                    while lookahead < len(lines) and not lines[lookahead].strip():
                        lookahead += 1
                    if lookahead < len(lines):
                        next_indent = get_block_indent(lines[lookahead])
                        if next_indent > base_indent:
                            block_end = lookahead
                            continue
                    break
                next_indent = get_block_indent(next_line)
                if next_indent <= base_indent:
                    break
                block_end += 1

            blocks.append({
                'title': title,
                'start': i,
                'end': block_end,
                'properties': props,
                'body_start': prop_end,
                'indent': base_indent,
            })
            i = block_end
        else:
            i += 1

    return blocks


def build_extracted_page(title: str, properties: list[tuple], body_lines: list[str],
                         base_indent: int, subcategory: str = '',
                         journal_date: str = '') -> str:
    """
    Build the content of an extracted page with YAML frontmatter.
    Injects type: for event-type pages (meetings, dives, lessons, therapy, coaching).
    Injects date: for meetings matching Fathom format.
    """
    yaml_lines = ['---']

    # Map subcategory to type value for event-type pages
    TYPE_MAP = {
        'dive': 'Dive',
        'lesson': 'Lesson',
        'meeting': 'Meeting',
        'therapy': 'Therapy',
        'coaching': 'Coaching',
    }

    # For meetings: inject topic from title, date from journal filename
    if subcategory == 'meeting':
        yaml_lines.append(f"topic: {title}")
        if journal_date:
            date_formatted = journal_date.replace('_', '-')
            yaml_lines.append(f"date: {date_formatted}")

    # For therapy/coaching: inject date and attendees from title
    if subcategory in ('therapy', 'coaching'):
        if journal_date:
            date_formatted = journal_date.replace('_', '-')
            yaml_lines.append(f"date: {date_formatted}")
        # Extract person name from title (may have date prefix):
        # "2026_01_26 - Therapy with Example Person B" or "Therapy with Example Person B" → Example Person B
        tc_title_match = re.search(
            r'(?:Therapy|Coaching)\s+with\s+(.*)',
            title, re.IGNORECASE
        )
        if tc_title_match:
            person = tc_title_match.group(1).strip()
            yaml_lines.append(f'attendees:\n  - "[[{person}]]"')

    # Inject type: for event-type pages
    if subcategory in TYPE_MAP:
        yaml_lines.append(f'type:\n  - "[[{TYPE_MAP[subcategory]}]]"')

    for key, raw_value in properties:
        norm_key = key.lower()
        if norm_key in JOURNAL_SKIP_PROPS:
            continue
        if norm_key in RENAME:
            norm_key = RENAME[norm_key]
        if norm_key == 'status' and (not raw_value or raw_value.strip() == ''):
            raw_value = 'read'
        # Dive properties are scalar (plain key: value)
        if norm_key in DIVE_PROPS or norm_key in ('buddy', 'max-depth'):
            # Keep wikilinks for location, dive-date, and buddy; strip for others
            DIVE_WIKILINK_PROPS = {'location', 'dive-date', 'buddy'}
            val = raw_value.strip()
            if is_date_property(norm_key):
                val = convert_date_in_wikilink(val)
            if norm_key not in DIVE_WIKILINK_PROPS:
                val = re.sub(r'^\[\[(.+)\]\]$', r'\1', val)
            yaml_lines.append(f"{norm_key}: {val}" if val else f"{norm_key}:")
            continue

        values = split_multi_values(raw_value)
        if is_date_property(norm_key):
            values = [convert_date_in_wikilink(v) for v in values]
        if norm_key in ('input', 'output'):
            values = [capitalize_type_value(v) for v in values]
        yaml_lines.append(format_yaml_value(norm_key, values))

    yaml_lines.append('---')

    # Dedent the body content relative to the block's base indent
    dedented_body = []
    for line in body_lines:
        # Remove base_indent + 1 levels of indentation
        stripped = line
        tabs_to_remove = base_indent + 1
        removed = 0
        result_line = ''
        for ch in stripped:
            if removed < tabs_to_remove and ch == '\t':
                removed += 1
            elif removed < tabs_to_remove and ch == ' ':
                removed += 0.25
            else:
                result_line += ch
        if not result_line.strip():
            dedented_body.append('\n')
        else:
            dedented_body.append(result_line if result_line.endswith('\n') else result_line + '\n')

    content = '\n'.join(yaml_lines) + '\n'
    if dedented_body:
        content += '\n'
        content += ''.join(dedented_body)

    return content


# ─── Journal-level frontmatter ──────────────────────────────────────

def extract_journal_frontmatter(lines: list[str]) -> tuple[list[tuple], int]:
    """
    Extract journal-level properties from the top of the file.
    These are properties like wake-up-time::, bed-time::, etc. that appear
    at the very start without bullet indentation.

    Also captures any top-level properties (even extractable ones like producer::, input::)
    when they appear at the file level rather than nested inside a bullet.

    Returns (properties, body_start_index).
    """
    properties = []
    body_start = 0
    prop_pattern = re.compile(r'^([a-zA-Z_-]+)::\s*(.*)')

    for i, line in enumerate(lines):
        stripped = line.strip()
        if not stripped:
            if properties:
                body_start = i
            continue
        # Skip empty Logseq bullets ("-" alone) at the top of the file
        if stripped == '-':
            body_start = i + 1
            continue
        # Skip hashtag-only lines at top (e.g. "#quotes")
        if re.match(r'^#\S', stripped) and '::' not in stripped:
            # This is a hashtag tag, not a property — skip but keep scanning
            body_start = i + 1
            continue
        m = prop_pattern.match(stripped)
        if m and not stripped.startswith('\t'):
            key = m.group(1).strip()
            value = m.group(2).strip()
            if key.lower() not in JOURNAL_SKIP_PROPS:
                properties.append((key, value))
            body_start = i + 1
        else:
            body_start = i
            break

    return properties, body_start


# ─── Logseq renderer removal ────────────────────────────────────────

def remove_logseq_renderers(lines: list[str]) -> list[str]:
    """Remove Logseq-specific renderer macros like {{renderer :wordcount_}}."""
    renderer_pattern = re.compile(r'\{\{renderer\s+:[^}]*\}\}')
    return [renderer_pattern.sub('', line) for line in lines]


# ─── Main journal conversion ────────────────────────────────────────

def convert_journal_file(input_path: Path, output_dir: Path,
                          extracted_pages_dir: Path,
                          block_id_map: dict, uuid_to_short: dict,
                          pages_block_id_map: dict = None,
                          pages_uuid_to_short: dict = None):
    """
    Convert a single journal file:
    1. Extract journal-level properties as frontmatter
    2. Find and extract blocks with properties into separate pages
    3. Convert date references, block embeds, BEGIN_QUOTE, collapsed
    4. Write the cleaned journal file
    """
    # Merge block ID maps (journals + pages)
    merged_block_map = dict(pages_block_id_map or {})
    merged_block_map.update(block_id_map)
    merged_uuid_short = dict(pages_uuid_to_short or {})
    merged_uuid_short.update(uuid_to_short)

    with open(input_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # Step 0: Handle any YAML frontmatter that already exists (some files have --- blocks)
    yaml_start = -1
    yaml_end = -1
    if lines and lines[0].strip() == '---':
        for idx in range(1, len(lines)):
            if lines[idx].strip() == '---':
                yaml_end = idx + 1
                break
        if yaml_end > 0:
            # Skip existing YAML frontmatter (it's usually just title)
            lines = lines[yaml_end:]

    # Step 1: Extract journal-level frontmatter
    journal_props, body_start = extract_journal_frontmatter(lines)
    body_lines = lines[body_start:]

    # Step 2: Find extractable blocks
    extractable = find_extractable_blocks(body_lines)

    # Step 3: Extract blocks into separate pages (process in reverse to preserve indices)
    # Get journal date from filename (e.g. "2024_01_15" from "2024_01_15.md")
    journal_date = input_path.stem

    extracted_titles = []
    for block in reversed(extractable):
        title = block['title']
        props = block['properties']
        block_body = body_lines[block['body_start']:block['end']]

        # Classify into folder and adjust title
        category_path, subcategory = classify_extracted_page(props, title)
        title = adjust_title(title, subcategory, journal_date)

        # Apply date conversion to the block body before extraction
        block_body = [convert_date_refs_in_line(line) for line in block_body]

        # Build the extracted page content
        page_content = build_extracted_page(title, props, block_body, block['indent'],
                                                  subcategory, journal_date)

        # Write the extracted page into the appropriate category folder
        safe_title = sanitize_page_title(title)
        page_path = extracted_pages_dir / category_path / f"{safe_title}.md"
        page_path.parent.mkdir(parents=True, exist_ok=True)
        with open(page_path, 'w', encoding='utf-8') as f:
            f.write(page_content)

        # Replace the block in the journal with a wikilink
        indent_prefix = ''
        orig_line = body_lines[block['start']]
        # Preserve the original indent
        for ch in orig_line:
            if ch in ('\t', ' '):
                indent_prefix += ch
            else:
                break
        # Check if it started with a bullet
        if orig_line.strip().startswith('-'):
            replacement = f"{indent_prefix}- [[{title}]]\n"
        else:
            replacement = f"{indent_prefix}[[{title}]]\n"

        body_lines[block['start']:block['end']] = [replacement]
        extracted_titles.append(title)

    # Step 4: Apply transformations to the remaining journal body
    body_lines = remove_collapsed_lines(body_lines)
    body_lines = convert_org_blocks(body_lines)
    body_lines = remove_logseq_renderers(body_lines)
    body_lines = convert_block_embeds(body_lines, merged_block_map, merged_uuid_short)
    body_lines = convert_block_refs(body_lines, merged_block_map, merged_uuid_short)

    # Convert date references in every line
    body_lines = [convert_date_refs_in_line(line) for line in body_lines]

    # Step 5: Build output
    output_lines = []

    # Add journal-level frontmatter if there are properties
    if journal_props:
        output_lines.append('---\n')
        for key, value in journal_props:
            norm_key = key.lower().replace('_', '-')
            # Apply rename logic (input → type, tags → backlinks, etc.)
            if norm_key in RENAME:
                norm_key = RENAME[norm_key]
            # Apply proper YAML formatting for list-type properties
            if norm_key in SCALAR_PROPS:
                values = split_multi_values(value)
                output_lines.append(format_yaml_value(norm_key, values) + '\n')
            elif norm_key in ('input', 'output'):
                values = split_multi_values(value)
                values = [capitalize_type_value(v) for v in values]
                output_lines.append(format_yaml_value(norm_key, values) + '\n')
            elif norm_key in ('backlinks', 'source', 'producer', 'relates-to', 'reference', 'attendees'):
                values = split_multi_values(value)
                output_lines.append(format_yaml_value(norm_key, values) + '\n')
            elif is_date_property(norm_key):
                values = split_multi_values(value)
                values = [convert_date_in_wikilink(v) for v in values]
                output_lines.append(format_yaml_value(norm_key, values) + '\n')
            elif norm_key == 'status' and (not value or value.strip() == ''):
                output_lines.append(f"{norm_key}: read\n")
            else:
                output_lines.append(f"{norm_key}: {value}\n")
        output_lines.append('---\n')

    output_lines.extend(body_lines)

    # Write the journal file
    output_path = output_dir / input_path.name
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as f:
        f.writelines(output_lines)

    return extracted_titles


def sanitize_page_title(title: str) -> str:
    """Sanitize a title for use as a filename."""
    # Remove or replace characters that aren't valid in filenames
    title = title.replace('/', '_')
    title = title.replace('\\', '_')
    title = title.replace(':', ' -')
    title = title.replace('?', '')
    title = title.replace('"', "'")
    title = title.replace('|', '-')
    title = title.replace('<', '')
    title = title.replace('>', '')
    title = title.replace('*', '')
    title = title.strip()
    # Truncate to avoid filesystem limits (max ~200 chars to leave room for path + .md)
    if len(title) > 200:
        title = title[:197] + '...'
    return title


# ─── Folder conversion ──────────────────────────────────────────────

def convert_journals_folder(input_dir: Path, output_dir: Path,
                             pages_dir: Path = None,
                             file_list: list[str] = None):
    """Convert all journal files in a folder."""
    output_dir.mkdir(parents=True, exist_ok=True)
    extracted_dir = output_dir / '_extracted_pages'
    extracted_dir.mkdir(parents=True, exist_ok=True)

    # Build block ID map from journals
    print("Building block ID map from journals...")
    block_id_map, uuid_to_short = build_block_id_map(input_dir)
    print(f"  Found {len(block_id_map)} block IDs in journals")

    # Also build from pages if available
    pages_block_id_map = {}
    pages_uuid_to_short = {}
    if pages_dir and pages_dir.exists():
        print("Building block ID map from pages...")
        pages_block_id_map, pages_uuid_to_short = build_block_id_map(pages_dir)
        print(f"  Found {len(pages_block_id_map)} block IDs in pages")

    if file_list:
        files = [input_dir / f for f in file_list]
    else:
        files = sorted(input_dir.glob('*.md'))

    converted = 0
    total_extracted = 0

    errors = []
    for fpath in files:
        if not fpath.exists():
            print(f"  SKIP (not found): {fpath.name}")
            continue

        try:
            extracted = convert_journal_file(
                fpath, output_dir, extracted_dir,
                block_id_map, uuid_to_short,
                pages_block_id_map, pages_uuid_to_short,
            )
            converted += 1
            n_extracted = len(extracted)
            total_extracted += n_extracted

            status = f"   OK: {fpath.name}"
            if n_extracted:
                status += f" ({n_extracted} pages extracted)"
            print(status)
        except Exception as e:
            errors.append((fpath.name, str(e)))
            print(f"  ERROR: {fpath.name} — {e}")

    print(f"\nConverted {converted} journal files → {output_dir}")
    print(f"Extracted {total_extracted} pages → {extracted_dir}")
    if errors:
        print(f"\n{len(errors)} ERRORS:")
        for fname, err in errors:
            print(f"  {fname}: {err}")


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

if __name__ == '__main__':
    SAMPLE_FILES = []  # Configure only from a reviewed fictional test mapping.

    input_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path('CONFIGURE_REVIEWED_COPY_PATH')
    output_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path('CONFIGURE_REVIEWED_COPY_PATH')
    pages_dir = Path('CONFIGURE_REVIEWED_COPY_PATH')

    print(f"Converting journals from: {input_dir}")
    print(f"Output to: {output_dir}\n")

    convert_journals_folder(input_dir, output_dir, pages_dir, SAMPLE_FILES)
