# 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
"""
Tana → Obsidian Migration Script
Converts a Tana export into Obsidian-compatible markdown files,
split into Personal and Work vaults.
"""

import os
import re
import json
from pathlib import Path
from collections import defaultdict
from datetime import datetime

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

TANA_EXPORT = Path('CONFIGURE_REVIEWED_COPY_PATH')
OUTPUT_BASE = Path('CONFIGURE_REVIEWED_COPY_PATH')
PERSONAL_OUT = OUTPUT_BASE / "Personal"
WORK_OUT = OUTPUT_BASE / "Work"
TRACKING_OUT = PERSONAL_OUT / "_Tracking"

WORK_PROJECTS = set()  # Configure only from a reviewed fictional test mapping.

# Types that are Tana internal artifacts — drop entirely
DROP_TYPES = {
    "status", "priority", "prioritisation", "genre", "genre refinement",
    "task values", "impact prioritisation", "enthusiasm prioritisation",
    "effort prioritisation", "scope", "energy", "interval",
    "calendar interval", "example", "example supertag",
    "example search supertag", "example information",
    "medium", "session type", "values",
}

# Numbered-only types (Tana artifacts)
NUMBERED_RE = re.compile(r'^\d+$')

# Types to aggregate into single list files
LIST_TYPES = {
    "idea": ("_MOCs", "Ideas.md"),
    "radar": ("_MOCs", "Radar.md"),
    "to buy": ("_MOCs", "To Buy.md"),
    "to research": ("_MOCs", "To Research.md"),
    "goal": ("_TRACKING_", "Goals.md"),
    "learning goals": ("_TRACKING_", "Goals.md"),
    "habits": ("_TRACKING_", "Habits and Tracking.md"),
    "bucket list item": ("_MOCs", "Bucket List.md"),
    "impossible list": ("_MOCs", "Bucket List.md"),
    "time-off idea": ("_MOCs", "Time Off Ideas.md"),
    "date ideas": ("_MOCs", "Time Off Ideas.md"),
    "connect": ("_MOCs", "Connect.md"),
    "decision": ("_MOCs", "Decisions.md"),
    "dream analysis": ("Personal", "Dreams.md"),
    "guitar practice": ("Personal", "Guitar.md"),
    "restaurant": ("Personal", "Restaurants.md"),
    "accommodation": ("Personal", "Restaurants.md"),
    "experiment": ("Reference", "Experiments.md"),
    "blog posts": ("Content/Drafts", "Blog Drafts.md"),
    "tweet": ("Content/Drafts", "Twitter Drafts.md"),
    "twitter thread": ("Content/Drafts", "Twitter Drafts.md"),
    "articles": ("Content/Drafts", "Blog Drafts.md"),
}

# Types that get individual files in Content/
CONTENT_TYPES = {
    "book": "Content/Books",
    "movie - show": "Content/Movies",
    "video": "Content/Videos",
    "youtube video": "Content/Videos",
    "podcast": "Content/Podcasts",
    "email reply": "Content/Email Replies",
    "lesson": "Content/Lessons",
    "courses": "Content/Lessons",
    "book review": "_MERGE_BOOK_",  # special: merge into book file
}

# Types that get individual files in Projects/
PROJECT_TYPE = "project"
CHUNK_TYPE = "chunk"

# Types for people
PEOPLE_TYPES = {"person", "friend", "contact", "producer"}

# ─── Parsing Utilities ───────────────────────────────────────────────────────

def extract_type_from_filename(filename):
    """Extract type tags from filename like 'Name(type1) (type2).md'"""
    stem = filename
    if stem.endswith('.md'):
        stem = stem[:-3]
    types = re.findall(r'\(([^)]+)\)', stem)
    # Filter out date-like patterns (e.g. "Wed, 29 Mar 2023")
    filtered = []
    for t in types:
        t = t.strip()
        # Skip if it looks like a date
        if re.match(r'(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s+\d', t):
            continue
        if re.match(r'\d{4}-\d{2}-\d{2}', t):
            continue
        # Skip if it's a pure parenthetical like "old" or "e.g. ..."
        if t.lower() in ('old', 'new'):
            continue
        filtered.append(t)
    return filtered

def extract_name_from_filename(filename):
    """Extract clean name from filename, removing type tags"""
    stem = filename
    if stem.endswith('.md'):
        stem = stem[:-3]
    # Remove all (type) annotations
    name = re.sub(r'\s*\([^)]*\)', '', stem).strip()
    # Remove leading checkbox markers
    name = re.sub(r'^\[[ x]\]\s*', '', name)
    return name

def sanitize_filename(name):
    """Make a string safe for use as a filename"""
    # Remove/replace problematic characters
    name = name.replace('/', ' - ')
    name = name.replace('\\', ' - ')
    name = name.replace(':', ' -')
    name = name.replace('"', "'")
    name = name.replace('|', '-')
    name = name.replace('?', '')
    name = name.replace('*', '')
    name = name.replace('<', '')
    name = name.replace('>', '')
    name = name.replace('\n', ' ')
    # Collapse multiple spaces
    name = re.sub(r'\s+', ' ', name).strip()
    # Truncate very long names
    if len(name) > 120:
        name = name[:120].strip()
    return name

def convert_tana_links(content):
    """Convert Tana relative links to Obsidian wikilinks.
    [Display Text](<relative/path/to/file.md>) → [[Display Text]]
    """
    def replace_link(match):
        display = match.group(1).strip()
        # Clean up display text - remove type annotations
        display = re.sub(r'\s*#\w[\w\s/]*', '', display).strip()
        if display:
            return f"[[{display}]]"
        return match.group(0)

    # Pattern: [text](<path>) — Tana uses angle brackets around relative paths
    content = re.sub(r'\[([^\]]+)\]\(<[^>]+>\)', replace_link, content)
    # Also handle [text](path) without angle brackets (some Tana links)
    # But only for relative paths, not URLs
    def replace_relative_link(match):
        display = match.group(1).strip()
        path = match.group(2).strip()
        if path.startswith('http') or path.startswith('//'):
            return match.group(0)  # keep URLs
        display = re.sub(r'\s*#\w[\w\s/]*', '', display).strip()
        if display:
            return f"[[{display}]]"
        return match.group(0)

    content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', replace_relative_link, content)
    return content

def extract_metadata(content):
    """Extract Tana metadata fields from content.
    Returns (metadata_dict, cleaned_content).
    Metadata fields are lines like: - **Field**: value
    """
    metadata = {}
    cleaned_lines = []
    lines = content.split('\n')

    for line in lines:
        # Match metadata fields: - **Field Name**: value or - **Field** _(desc)_: value
        m = re.match(r'^-\s+\*\*([^*]+)\*\*(?:\s*_\([^)]*\)_)?\s*:\s*(.*)', line)
        if m:
            key = m.group(1).strip()
            val = m.group(2).strip()
            # Normalize key
            key_norm = key.lower().replace(' ', '-')

            # Extract value from link if present
            link_match = re.search(r'\[([^\]]+)\]', val)
            if link_match:
                val = link_match.group(1).strip()

            # Clean hash tags from value
            val = re.sub(r'\s*#\w[\w\s/]*', '', val).strip()

            if key_norm in metadata and metadata[key_norm]:
                # Append if key already exists
                if isinstance(metadata[key_norm], list):
                    metadata[key_norm].append(val)
                else:
                    metadata[key_norm] = [metadata[key_norm], val]
            else:
                metadata[key_norm] = val
        else:
            cleaned_lines.append(line)

    return metadata, '\n'.join(cleaned_lines)

def extract_first_line_info(content):
    """Extract checkbox state and title from first line of Tana content."""
    lines = content.strip().split('\n')
    if not lines:
        return None, False, ""

    first = lines[0]
    done = first.startswith('[x]')
    undone = first.startswith('[ ]')
    checkbox = done or undone

    # Remove checkbox and hash tags from title
    title = re.sub(r'^\[[ x]\]\s*', '', first)
    title = re.sub(r'\s*#[\w\s/]+', '', title).strip()

    remaining = '\n'.join(lines[1:]) if len(lines) > 1 else ""

    return title, done, remaining

def merge_folder_content(folder_path, depth=0):
    """Recursively merge a folder's README.md with all child files/folders.
    Returns aggregated content as a string with proper indentation.
    """
    readme_path = folder_path / "README.md"
    parts = []

    # Read README (parent content)
    if readme_path.exists():
        content = readme_path.read_text(encoding='utf-8', errors='replace')
        # Remove lines that are just links to child READMEs
        lines = content.split('\n')
        filtered = []
        for line in lines:
            # Skip lines that are just navigation links to subfolders
            if re.match(r'^-\s*\[.*\]\(.*README\.md\)$', line.strip()):
                continue
            filtered.append(line)
        parts.append('\n'.join(filtered))

    # Process child files and folders
    children = sorted(folder_path.iterdir())
    for child in children:
        if child.name == "README.md":
            continue
        if child.is_file() and child.suffix == '.md':
            child_content = child.read_text(encoding='utf-8', errors='replace')
            parts.append(child_content)
        elif child.is_dir():
            sub_content = merge_folder_content(child, depth + 1)
            if sub_content.strip():
                parts.append(sub_content)

    return '\n'.join(parts)

def normalize_indent(content):
    """Convert spaces-based indentation to tabs (Obsidian prefers tabs)."""
    lines = content.split('\n')
    result = []
    for line in lines:
        # Count leading spaces (Tana uses 2-space indentation)
        stripped = line.lstrip(' ')
        spaces = len(line) - len(stripped)
        tabs = spaces // 2
        result.append('\t' * tabs + stripped)
    return '\n'.join(result)


def promote_sections_to_headers(content, level=2):
    """Convert top-level Tana bullet items into markdown headers.

    In Tana exports, the top-level bullet points of a project or meeting
    represent logical sections (e.g. "Outputs:", "Project context",
    "Next steps"). This function promotes them to ## headers so the note
    has real structure in Obsidian rather than one giant nested bullet list.

    A top-level bullet is promoted when it:
      - Has indented children below it, OR
      - Ends with ':', OR
      - Looks like a named section (title-case or multi-word without URL/image)
    Single-word, URL, or image lines are left as bullets.
    """
    lines = content.split('\n')
    hashes = '#' * level

    # Pre-scan: which line indices have a child at deeper indent?
    def indent_depth(line):
        stripped = line.lstrip('\t')
        return len(line) - len(stripped)

    has_children = set()
    for i, line in enumerate(lines):
        if indent_depth(line) == 0 and line.startswith('- '):
            # Look ahead for an indented child
            for j in range(i + 1, len(lines)):
                next_line = lines[j]
                if not next_line.strip():
                    continue
                if indent_depth(next_line) > 0:
                    has_children.add(i)
                break  # stop at first non-blank

    result = []
    for i, line in enumerate(lines):
        if indent_depth(line) == 0 and line.startswith('- '):
            text = line[2:].strip()
            # Skip metadata-style lines (already extracted, but defensive)
            if re.match(r'\*\*[^*]+\*\*', text):
                result.append(line)
                continue
            # Skip image lines
            if text.startswith('!['):
                result.append(line)
                continue
            # Skip plain URLs
            if text.startswith('http') or text.startswith('[http'):
                result.append(line)
                continue
            # Promote if it has children OR ends with ':'
            ends_colon = text.endswith(':')
            if i in has_children or ends_colon:
                header_text = text.rstrip(':').strip()
                if header_text:
                    result.append(f'\n{hashes} {header_text}')
                    continue
        result.append(line)

    return '\n'.join(result).strip()

def clean_content(content):
    """Clean Tana-specific artifacts from content."""
    # Remove HTML comments (Tana ref IDs)
    content = re.sub(r'<!--\s*ref:[^>]+-->', '', content)
    # Remove Tana hash tags from first line (type annotations)
    lines = content.split('\n')
    if lines:
        # Clean first line of hash tags but keep the rest
        lines[0] = re.sub(r'\s*#[\w\s/·]+(?=\s|$)', '', lines[0])
    content = '\n'.join(lines)
    return content

# ─── YAML Frontmatter Generators ────────────────────────────────────────────

def yaml_val(val, as_wikilink=False):
    """Format a value for YAML frontmatter."""
    if not val:
        return ""
    if as_wikilink:
        return f'"[[{val}]]"'
    return val

def yaml_list(vals, as_wikilink=False):
    """Format a list for YAML frontmatter."""
    if not vals:
        return "\n"
    if isinstance(vals, str):
        vals = [vals]
    lines = []
    for v in vals:
        if v:
            if as_wikilink:
                lines.append(f'  - "[[{v}]]"')
            else:
                lines.append(f'  - {v}')
    if lines:
        return '\n' + '\n'.join(lines) + '\n'
    return "\n"

def make_book_yaml(metadata):
    producer = metadata.get('producer', '')
    input_type = '  - "[[Books]]"'
    status = metadata.get('status', metadata.get('reading-status', ''))
    recommended = metadata.get('recommended-by', '')
    rating = metadata.get('rating', '')
    genre = metadata.get('genre', '')
    backlinks = metadata.get('topics', '')

    lines = ["---"]
    lines.append(f"producer:{yaml_list(producer, as_wikilink=bool(producer))}")
    lines.append(f"input:\n{input_type}")
    lines.append(f"status:{yaml_list(status)}")
    lines.append(f"recommended-by:{yaml_list(recommended, as_wikilink=bool(recommended))}")
    lines.append(f"rating: {rating}" if rating else "rating:")
    lines.append(f"genre:{yaml_list(genre)}")
    lines.append(f"backlinks:{yaml_list(backlinks, as_wikilink=bool(backlinks))}")
    lines.append("---")
    return '\n'.join(lines)

def make_movie_yaml(metadata):
    """Minimal movie/show YAML — just status, recommended-by, genre."""
    genre = metadata.get('film-genre', metadata.get('genre', ''))
    recommended = metadata.get('recommended-by', '')
    status = metadata.get('status', '')

    lines = ["---"]
    lines.append(f"status:{yaml_list(status)}")
    lines.append(f"recommended-by:{yaml_list(recommended, as_wikilink=bool(recommended))}")
    lines.append(f"genre:{yaml_list(genre)}")
    lines.append("---")
    return '\n'.join(lines)

def make_video_yaml(metadata):
    producer = metadata.get('producer', '')
    link = metadata.get('url', metadata.get('website-or-link', ''))
    backlinks = metadata.get('topics', '')

    lines = ["---"]
    lines.append(f"input:\n  - \"[[Videos]]\"")
    lines.append(f"producer:{yaml_list(producer, as_wikilink=bool(producer))}")
    lines.append(f"link: {link}" if link else "link:")
    lines.append(f"backlinks:{yaml_list(backlinks, as_wikilink=bool(backlinks))}")
    lines.append("---")
    return '\n'.join(lines)

def make_podcast_yaml(metadata):
    producer = metadata.get('producer', '')
    link = metadata.get('url', metadata.get('website-or-link', ''))
    recommended = metadata.get('recommended-by', '')
    backlinks = metadata.get('topics', '')

    lines = ["---"]
    lines.append(f"input:\n  - \"[[Podcasts]]\"")
    lines.append(f"producer:{yaml_list(producer, as_wikilink=bool(producer))}")
    lines.append(f"link: {link}" if link else "link:")
    lines.append(f"recommended-by:{yaml_list(recommended, as_wikilink=bool(recommended))}")
    lines.append(f"backlinks:{yaml_list(backlinks, as_wikilink=bool(backlinks))}")
    lines.append("---")
    return '\n'.join(lines)

def make_project_yaml(metadata):
    status = metadata.get('status', '')
    relates = metadata.get('relates-to', '')
    backlinks = metadata.get('topics', '')

    lines = ["---"]
    lines.append(f"output:\n  - \"[[Projects]]\"")
    lines.append(f"status:{yaml_list(status)}")
    lines.append(f"relates-to:{yaml_list(relates, as_wikilink=bool(relates))}")
    lines.append(f"backlinks:{yaml_list(backlinks, as_wikilink=bool(backlinks))}")
    lines.append("---")
    return '\n'.join(lines)

def extract_attendees_from_body(body):
    """Extract attendees from body wikilinks when metadata doesn't list them.
    Library meetings often have attendees as bulleted [[wikilinks]] rather than fields.
    Returns a list of unique attendee names (order preserved)."""
    if not body:
        return []
    seen = set()
    attendees = []
    # Match wikilinks in the first ~15 lines (attendees are usually at top)
    lines = body.strip().split('\n')[:20]
    for line in lines:
        # Look for top-level bulleted wikilinks like "- [[Name]]"
        for match in re.finditer(r'\[\[([^\]|#]+?)(?:\|[^\]]+)?\]\]', line):
            name = match.group(1).strip()
            # Filter out non-person links (dates, topics, URLs)
            if (len(name) < 80 and
                    not re.match(r'\d{4}', name) and
                    not name.startswith('http') and
                    name not in seen):
                seen.add(name)
                attendees.append(name)
    return attendees


def make_meeting_yaml(metadata, date_str="", topic="", body=""):
    attendees = metadata.get('attendees', '')
    relates = metadata.get('relates-to', '')

    # If no attendees in metadata, try to extract from body wikilinks
    if not attendees and body:
        extracted = extract_attendees_from_body(body)
        if extracted:
            attendees = extracted

    lines = ["---"]
    lines.append(f"topic: {topic}" if topic else "topic:")
    lines.append(f"date: {date_str}" if date_str else "date:")
    lines.append(f"type:\n  - \"[[Meeting]]\"")
    lines.append(f"attendees:{yaml_list(attendees, as_wikilink=bool(attendees))}")
    lines.append(f"relates-to:{yaml_list(relates, as_wikilink=bool(relates))}")
    lines.append("---")
    return '\n'.join(lines)

def make_email_reply_yaml(metadata):
    lines = ["---"]
    lines.append(f"type:\n  - \"[[Email Reply]]\"")
    lines.append("---")
    return '\n'.join(lines)

def make_area_yaml(metadata):
    topics = metadata.get('topics', '')
    relates = metadata.get('relates-to', '')
    lines = ["---"]
    lines.append(f"type:\n  - \"[[Area]]\"")
    lines.append(f"topics:{yaml_list(topics, as_wikilink=bool(topics))}")
    lines.append(f"relates-to:{yaml_list(relates, as_wikilink=bool(relates))}")
    lines.append("---")
    return '\n'.join(lines)

def make_initiative_yaml(metadata):
    status = metadata.get('status', '')
    relates = metadata.get('relates-to', '')
    overview = metadata.get('overview', '')
    next_steps = metadata.get('next-steps', '')
    lines = ["---"]
    lines.append(f"type:\n  - \"[[Initiative]]\"")
    lines.append(f"status:{yaml_list(status)}")
    lines.append(f"relates-to:{yaml_list(relates, as_wikilink=bool(relates))}")
    lines.append("---")
    return '\n'.join(lines)

# ─── Main Processing ─────────────────────────────────────────────────────────

class TanaMigrator:
    def __init__(self):
        self.stats = defaultdict(int)
        self.list_items = defaultdict(list)  # (folder, filename) → list of items
        self.project_tasks = defaultdict(list)  # project_name → list of task content
        self.project_chunks = defaultdict(list)  # project_name → list of chunk content
        self.people_discuss = defaultdict(list)  # person_name → list of discuss items
        self.book_reviews = {}  # book_name → review content
        self.books = {}  # book_name → (yaml, content, path)
        self.projects = {}  # project_name → (yaml, content, vault)
        self.areas = {}  # area_name → {"yaml", "content", "vault", "metadata"}
        self.initiatives = {}  # initiative_name → {"yaml", "content", "vault", "metadata"}
        self.weekly_tasks = defaultdict(lambda: {"done": [], "open": []})
        self.open_orphan_tasks = []
        self.uncategorized = []

    def run(self):
        """Main entry point."""
        print("=" * 60)
        print("Tana → Obsidian Migration")
        print("=" * 60)

        # Create output directories
        self._create_dirs()

        # Phase 1: Process all files and collect data
        print("\n[Phase 1] Scanning and processing files...")
        self._process_daily_notes()
        self._process_library()
        self._process_special_sections()

        # Phase 2: Write output files
        print("\n[Phase 2] Writing output files...")
        self._write_projects()
        self._write_areas()
        self._write_initiatives()
        self._write_list_files()
        self._write_weekly_journals()
        self._write_open_tasks()
        self._write_uncategorized()

        # Phase 3: Merge book reviews into books
        print("\n[Phase 3] Merging book reviews into books...")
        self._merge_book_reviews()

        # Print stats
        print("\n" + "=" * 60)
        print("Migration Complete!")
        print("=" * 60)
        for key, val in sorted(self.stats.items()):
            print(f"  {key}: {val}")

    def _create_dirs(self):
        dirs = [
            PERSONAL_OUT / "Content" / "Books",
            PERSONAL_OUT / "Content" / "Movies",
            PERSONAL_OUT / "Content" / "Videos",
            PERSONAL_OUT / "Content" / "Podcasts",
            PERSONAL_OUT / "Content" / "Email Replies",
            PERSONAL_OUT / "Content" / "Drafts",
            PERSONAL_OUT / "Content" / "Lessons",
            PERSONAL_OUT / "Projects",
            PERSONAL_OUT / "Areas",
            PERSONAL_OUT / "Initiatives",
            PERSONAL_OUT / "People",
            PERSONAL_OUT / "_MOCs",
            PERSONAL_OUT / "Personal",
            PERSONAL_OUT / "Activities" / "Sessions",
            PERSONAL_OUT / "_Journals" / "00_Journals_Daily",
            PERSONAL_OUT / "Reference",
            PERSONAL_OUT / "Uncategorized",
            WORK_OUT / "Meetings",
            WORK_OUT / "Projects",
            WORK_OUT / "Areas",
            WORK_OUT / "Initiatives",
            WORK_OUT / "People",
            TRACKING_OUT / "Weekly",
        ]
        for d in dirs:
            d.mkdir(parents=True, exist_ok=True)

    # ── Daily Notes Processing ────────────────────────────────────────────

    def _process_daily_notes(self):
        daily_root = TANA_EXPORT / 'Example Workspace' / "Daily notes"
        if not daily_root.exists():
            print("  WARNING: Daily notes folder not found")
            return

        for year_dir in sorted(daily_root.iterdir()):
            if not year_dir.is_dir():
                continue
            for week_dir in sorted(year_dir.iterdir()):
                if not week_dir.is_dir():
                    continue
                # Extract week number for weekly journals
                week_match = re.search(r'Week (\d+)', week_dir.name)
                week_num = int(week_match.group(1)) if week_match else None
                year = year_dir.name

                for day_entry in sorted(week_dir.iterdir()):
                    if day_entry.name == "README.md":
                        continue
                    self._process_day(day_entry, year, week_num)

    def _process_day(self, day_entry, year, week_num):
        """Process a single day — either a .md file or a folder."""
        # Extract date from name like "2024-05-15 - Wednesday"
        date_match = re.match(r'(\d{4}-\d{2}-\d{2})\s*-\s*(\w+)', day_entry.name.replace('.md', ''))
        if not date_match:
            return
        date_str = date_match.group(1)
        day_name = date_match.group(2)
        date_underscore = date_str.replace('-', '_')
        week_key = f"{year}_W{week_num:02d}" if week_num else f"{year}_unknown"

        if day_entry.is_file() and day_entry.suffix == '.md':
            # Simple day file — read content, check for typed items
            content = day_entry.read_text(encoding='utf-8', errors='replace')
            content = clean_content(content)
            content = convert_tana_links(content)
            # Write as daily journal
            journal_content = f"- ## Journal\n{self._indent_content(content)}"
            self._write_file(
                PERSONAL_OUT / "_Journals" / "00_Journals_Daily" / f"{date_underscore}.md",
                journal_content
            )
            self.stats["daily_journals"] += 1

        elif day_entry.is_dir():
            # Day folder — process children, extract typed items
            journal_lines = []
            readme = day_entry / "README.md"
            if readme.exists():
                readme_content = readme.read_text(encoding='utf-8', errors='replace')
                # First line is the day name, skip it
                lines = readme_content.strip().split('\n')
                for line in lines[1:]:
                    # Skip navigation links to child READMEs
                    if re.match(r'^-\s*\[.*\]\(.*README\.md\)$', line.strip()):
                        continue
                    if re.match(r'^-\s*\[.*\]\(.*\.md\)$', line.strip()):
                        continue
                    journal_lines.append(line)

            # Process child items
            for child in sorted(day_entry.iterdir()):
                if child.name == "README.md":
                    continue
                if child.is_file() and child.suffix == '.md':
                    self._route_typed_item(child, date_str, week_key, journal_lines)
                elif child.is_dir():
                    self._route_typed_folder(child, date_str, week_key, journal_lines)

            # Write daily journal with remaining untyped content
            if journal_lines:
                cleaned = '\n'.join(journal_lines).strip()
                if cleaned:
                    cleaned = clean_content(cleaned)
                    cleaned = convert_tana_links(cleaned)
                    journal_content = cleaned
                    self._write_file(
                        PERSONAL_OUT / "_Journals" / "00_Journals_Daily" / f"{date_underscore}.md",
                        journal_content
                    )
                    self.stats["daily_journals"] += 1

    def _route_typed_item(self, filepath, date_str, week_key, journal_lines):
        """Route a typed .md file to its destination."""
        types = extract_type_from_filename(filepath.name)
        name = extract_name_from_filename(filepath.name)
        content = filepath.read_text(encoding='utf-8', errors='replace')
        content = clean_content(content)

        primary_type = types[0] if types else None

        # Check if it's a numbered artifact or drop type
        if primary_type and (NUMBERED_RE.match(primary_type) or primary_type in DROP_TYPES):
            self.stats["dropped"] += 1
            return

        if not primary_type:
            # No type in filename — try detecting from content
            detected = self._detect_type_from_content(content)
            if detected:
                primary_type = detected
                types = [detected]
            else:
                # Truly untyped — keep in journal
                content = convert_tana_links(content)
                journal_lines.append(content)
                return

        # Route by type
        self._route_by_type(primary_type, name, content, date_str, week_key, types)

    def _route_typed_folder(self, folder_path, date_str, week_key, journal_lines):
        """Route a typed folder (with README + children) to its destination."""
        types = extract_type_from_filename(folder_path.name)
        name = extract_name_from_filename(folder_path.name)

        primary_type = types[0] if types else None

        if primary_type and (NUMBERED_RE.match(primary_type) or primary_type in DROP_TYPES):
            self.stats["dropped"] += 1
            return

        if not primary_type:
            # Untyped folder — recursively look for typed children first
            found_typed = self._process_folder_recursive_daily(folder_path, date_str, week_key, journal_lines)
            if not found_typed:
                # No typed children found — inline folder content into journal
                content = merge_folder_content(folder_path)
                content = clean_content(content)
                content = convert_tana_links(content)
                journal_lines.append(content)
            return

        # Container types: create file from README, then recurse for typed children.
        # This prevents typed children (tasks, decisions, sub-projects) from being
        # silently merged into the parent's content blob.
        DAILY_CONTAINER_TYPES = {"initiative", "area", "project", "module", "breakdown"}
        if primary_type in DAILY_CONTAINER_TYPES:
            readme = folder_path / "README.md"
            if readme.exists():
                content = readme.read_text(encoding='utf-8', errors='replace')
                content = clean_content(content)
                self._route_by_type(primary_type, name, content, date_str, week_key, types)
            else:
                # No README — merge only non-typed children as content
                content = merge_folder_content(folder_path)
                content = clean_content(content)
                self._route_by_type(primary_type, name, content, date_str, week_key, types)
            # Recurse into children for nested typed items
            self._process_folder_recursive_daily(folder_path, date_str, week_key, journal_lines)
            return

        # Other typed folder — merge and route (types like meeting, session, etc.
        # that don't typically contain independently-typed children)
        content = merge_folder_content(folder_path)
        content = clean_content(content)
        self._route_by_type(primary_type, name, content, date_str, week_key, types)

    def _process_folder_recursive_daily(self, folder_path, date_str, week_key, journal_lines):
        """Recursively process a folder within daily notes, routing typed items.
        Returns True if any typed items were found and routed."""
        found_typed = False
        for item in sorted(folder_path.iterdir()):
            if item.name == "README.md":
                continue
            if item.is_file() and item.suffix == '.md':
                types = extract_type_from_filename(item.name)
                if types:
                    name = extract_name_from_filename(item.name)
                    content = item.read_text(encoding='utf-8', errors='replace')
                    content = clean_content(content)
                    primary_type = types[0]
                    if NUMBERED_RE.match(primary_type) or primary_type in DROP_TYPES:
                        self.stats["dropped"] += 1
                    else:
                        self._route_by_type(primary_type, name, content, date_str, week_key, types)
                    found_typed = True
            elif item.is_dir():
                types = extract_type_from_filename(item.name)
                name = extract_name_from_filename(item.name)
                primary_type = types[0] if types else None

                RECURSE_TYPES = {"initiative", "area", "project", "module", "breakdown"}

                if primary_type and primary_type in RECURSE_TYPES:
                    # Container-type directory: create file from README, then recurse
                    readme = item / "README.md"
                    if readme.exists():
                        content = readme.read_text(encoding='utf-8', errors='replace')
                        content = clean_content(content)
                        self._route_by_type(primary_type, name, content, date_str, week_key, types)
                    self._process_folder_recursive_daily(item, date_str, week_key, journal_lines)
                    found_typed = True
                elif primary_type and not (NUMBERED_RE.match(primary_type) or primary_type in DROP_TYPES):
                    # Other typed directory: merge and route
                    content = merge_folder_content(item)
                    content = clean_content(content)
                    self._route_by_type(primary_type, name, content, date_str, week_key, types)
                    found_typed = True
                else:
                    # Untyped or drop-type directory: recurse
                    child_found = self._process_folder_recursive_daily(item, date_str, week_key, journal_lines)
                    if child_found:
                        found_typed = True
        return found_typed

    def _route_by_type(self, primary_type, name, content, date_str, week_key, all_types):
        """Central routing logic for typed items."""

        # ── List aggregation types ──
        if primary_type in LIST_TYPES:
            folder, filename = LIST_TYPES[primary_type]
            title, done, body = extract_first_line_info(content)
            display_name = name if name else title
            checkbox = "[x]" if done else "[ ]"
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            # Build list entry
            entry_lines = [f"- {checkbox} {display_name}"]
            if body.strip():
                for line in body.strip().split('\n'):
                    if line.strip():
                        entry_lines.append(f"\t{line}")
            self.list_items[(folder, filename)].append('\n'.join(entry_lines))
            self.stats[f"list_{primary_type}"] += 1
            return

        # ── Content types (individual files) ──
        if primary_type in CONTENT_TYPES:
            dest_folder = CONTENT_TYPES[primary_type]

            if dest_folder == "_MERGE_BOOK_":
                # Book review — store for later merging
                title, _, body = extract_first_line_info(content)
                metadata, body = extract_metadata(body)
                body = convert_tana_links(body)
                review_name = name if name else title
                self.book_reviews[review_name.lower()] = {
                    "name": review_name,
                    "producer": metadata.get('producer', ''),
                    "link": metadata.get('website-or-link', ''),
                    "content": body,
                }
                self.stats["book_reviews"] += 1
                return

            title, done, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            display_name = name if name else title

            # Generate appropriate YAML
            if primary_type == "book":
                yaml = make_book_yaml(metadata)
                self.books[display_name.lower()] = display_name
            elif primary_type == "movie - show":
                yaml = make_movie_yaml(metadata)
            elif primary_type in ("video", "youtube video"):
                yaml = make_video_yaml(metadata)
            elif primary_type == "podcast":
                yaml = make_podcast_yaml(metadata)
            elif primary_type == "email reply":
                yaml = make_email_reply_yaml(metadata)
            else:
                yaml = "---\n---"

            fname = sanitize_filename(display_name) + ".md"
            file_content = f"{yaml}\n\n{body.strip()}\n"
            self._write_file(PERSONAL_OUT / dest_folder / fname, file_content)
            self.stats[f"content_{primary_type}"] += 1
            return

        # ── Projects ──
        if primary_type == PROJECT_TYPE:
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            body = promote_sections_to_headers(body)
            display_name = name if name else title
            yaml = make_project_yaml(metadata)

            vault = "work" if self._is_work_project(display_name) else "personal"
            self.projects[display_name] = {
                "yaml": yaml,
                "content": body,
                "vault": vault,
                "metadata": metadata,
            }
            self.stats[f"projects_{vault}"] += 1
            return

        # ── Meetings ──
        if primary_type == "meeting":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            body = promote_sections_to_headers(body)
            display_name = name if name else title
            if date_str:
                date_fmt = date_str.replace('-', '_')
                topic = f"{date_fmt} - {display_name}"
            else:
                topic = display_name
            yaml = make_meeting_yaml(metadata, date_str, topic, body)
            fname = sanitize_filename(topic) + ".md"
            file_content = f"{yaml}\n\n{body.strip()}\n"
            self._write_file(WORK_OUT / "Meetings" / fname, file_content)
            self.stats["meetings"] += 1
            return

        # ── Tasks ──
        if primary_type == "task":
            self._process_task(name, content, date_str, week_key)
            return

        # ── Chunks ──
        if primary_type == CHUNK_TYPE:
            title, done, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            relates = metadata.get('relates-to', '')
            if relates:
                relates_key = relates[0] if isinstance(relates, list) else relates
                if relates_key:
                    checkbox = "[x]" if done else "[ ]"
                    entry = f"- {checkbox} **{display_name}**\n"
                    if body.strip():
                        for line in body.strip().split('\n'):
                            entry += f"\t{line}\n"
                    self.project_chunks[relates_key].append(entry)
            else:
                # Orphan chunk — treat as uncategorized
                content = convert_tana_links(content)
                self.uncategorized.append((display_name, content))
            self.stats["chunks"] += 1
            return

        # ── People ──
        if primary_type in PEOPLE_TYPES:
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            fname = sanitize_filename(display_name) + ".md"
            # Default to personal
            vault_out = PERSONAL_OUT / "People"
            file_content = body.strip() + "\n" if body.strip() else ""
            self._write_file(vault_out / fname, file_content)
            self.stats["people"] += 1
            return

        # ── Discuss items ──
        if primary_type == "discuss":
            title, done, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title

            # Try to extract person name from content
            person = self._extract_person_from_discuss(content, display_name)
            checkbox = "[x]" if done else "[ ]"
            entry = f"- {checkbox} {display_name}"
            if body.strip():
                entry += "\n" + '\n'.join(f"\t{l}" for l in body.strip().split('\n'))
            if person:
                self.people_discuss[person].append(entry)
            else:
                self.people_discuss["_unlinked"].append(entry)
            self.stats["discuss"] += 1
            return

        # ── Sessions (therapy/coaching) ──
        if primary_type == "sessions":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            fname = sanitize_filename(display_name) + ".md"
            self._write_file(PERSONAL_OUT / "Activities" / "Sessions" / fname, body.strip() + "\n")
            self.stats["sessions"] += 1
            return

        # ── Areas ──
        if primary_type == "area":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            body = promote_sections_to_headers(body)
            display_name = name if name else title
            yaml = make_area_yaml(metadata)

            vault = "work" if self._is_work_area(display_name) else "personal"
            self.areas[display_name] = {
                "yaml": yaml,
                "content": body,
                "vault": vault,
                "metadata": metadata,
            }
            self.stats[f"areas_{vault}"] += 1
            return

        # ── Initiatives ──
        if primary_type == "initiative":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            body = promote_sections_to_headers(body)
            display_name = name if name else title
            yaml = make_initiative_yaml(metadata)

            vault = "work" if self._is_work_initiative(display_name) else "personal"
            self.initiatives[display_name] = {
                "yaml": yaml,
                "content": body,
                "vault": vault,
                "metadata": metadata,
            }
            self.stats[f"initiatives_{vault}"] += 1
            return

        # ── SOPs ──
        if primary_type == "SOP":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            entry = f"## {display_name}\n\n{body.strip()}\n"
            self.list_items[("Reference", "SOPs.md")].append(entry)
            self.stats["sops"] += 1
            return

        # ── Products ──
        if primary_type == "product":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            link = metadata.get('website-or-link', '')
            entry = f"- **{display_name}**"
            if link:
                entry += f" — {link}"
            if body.strip():
                entry += "\n" + '\n'.join(f"\t{l}" for l in body.strip().split('\n'))
            self.list_items[("Reference", "Products.md")].append(entry)
            self.stats["products"] += 1
            return

        # ── Software functions ──
        if primary_type == "software functions":
            title, _, body = extract_first_line_info(content)
            body = convert_tana_links(body)
            display_name = name if name else title
            entry = f"## {display_name}\n\n{body.strip()}\n" if body.strip() else f"- {display_name}"
            self.list_items[("Reference", "Software Functions.md")].append(entry)
            self.stats["software_functions"] += 1
            return

        # ── Organizations ──
        if primary_type == "organization":
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            entry = f"- **{display_name}**"
            what = metadata.get('what-do-they-do?', '')
            link = metadata.get('website-or-link', '')
            if what:
                entry += f" — {what}"
            if link:
                entry += f" ({link})"
            self.list_items[("Reference", "Organisations.md")].append(entry)
            self.stats["organisations"] += 1
            return

        # ── Content-based rescue before uncategorized ──

        # Task-like content (first line starts with [ ] or [x])
        first_line = content.strip().split('\n')[0] if content.strip() else ""
        if first_line.startswith('[ ] ') or first_line.startswith('[x] '):
            self._process_task(name, content, date_str, week_key)
            self.stats["uncategorized_rescued_task"] += 1
            return

        # "to visit" items → restaurants/accommodation
        if '(to visit)' in content.lower() or '(to visit)' in (name or '').lower():
            title, done, body = extract_first_line_info(content)
            display_name = name if name else title
            # Clean up "(to visit)" from display name
            display_name = re.sub(r'\s*\(to visit\)\s*', '', display_name, flags=re.IGNORECASE).strip()
            checkbox = "[x]" if done else "[ ]"
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            entry_lines = [f"- {checkbox} {display_name}"]
            if body.strip():
                for line in body.strip().split('\n'):
                    if line.strip():
                        entry_lines.append(f"\t{line}")
            self.list_items[("Personal", "Restaurants.md")].append('\n'.join(entry_lines))
            self.stats["uncategorized_rescued_restaurant"] += 1
            return

        # Therapy/coaching session entries (have "Trigger or data" or self-compassion fields)
        if re.search(r'\*\*Trigger or data\*\*', content) or\
           (re.search(r'\*\*Mindful reflection\*\*', content) and re.search(r'\*\*Self-kindness\*\*', content)):
            title, _, body = extract_first_line_info(content)
            body = convert_tana_links(body)
            body = normalize_indent(body)
            display_name = name if name else title
            fname = sanitize_filename(display_name) + ".md"
            self._write_file(PERSONAL_OUT / "Activities" / "Sessions" / fname, body.strip() + "\n")
            self.stats["uncategorized_rescued_session"] += 1
            return

        # Calendar events with Attendees field → meetings
        if re.search(r'\*\*Attendees\*\*', content) and re.search(r'\*\*Event status\*\*', content):
            title, _, body = extract_first_line_info(content)
            metadata, body = extract_metadata(body)
            body = convert_tana_links(body)
            display_name = name if name else title
            # Try to extract date from content for naming
            date_match = re.search(r'(\d{4}-\d{2}-\d{2})', content)
            if date_match:
                meeting_date = date_match.group(1).replace('-', '_')
                fname = f"{meeting_date} - {sanitize_filename(display_name)}.md"
            else:
                fname = sanitize_filename(display_name) + ".md"
            attendees = metadata.get('attendees', '')
            topic = metadata.get('description', body.strip().split('\n')[0] if body.strip() else '')
            yaml_lines = ["---"]
            if date_str:
                yaml_lines.append(f"date: {date_str}")
            yaml_lines.append(f"topic: \"{display_name}\"")
            yaml_lines.append("type: \"[[Meeting]]\"")
            if attendees:
                if isinstance(attendees, list):
                    yaml_lines.append("attendees:")
                    for a in attendees:
                        yaml_lines.append(f"  - \"[[{a}]]\"")
                else:
                    yaml_lines.append(f"attendees:\n  - \"[[{attendees}]]\"")
            yaml_lines.append("---")
            yaml = '\n'.join(yaml_lines)
            self._write_file(WORK_OUT / "Meetings" / fname, f"{yaml}\n\n{body.strip()}\n")
            self.stats["uncategorized_rescued_meeting"] += 1
            return

        # ── Fallback: uncategorized ──
        content = convert_tana_links(content)
        self.uncategorized.append((name, content))
        self.stats["uncategorized"] += 1

    def _process_task(self, name, content, date_str, week_key):
        """Process a task item — route to project, weekly journal, or orphan list."""
        title, done, body = extract_first_line_info(content)
        metadata, body = extract_metadata(body)
        body = convert_tana_links(body)
        display_name = name if name else title

        relates = metadata.get('relates-to', '')
        status = metadata.get('status', '')
        priority = metadata.get('priority', '')

        checkbox = "[x]" if done else "[ ]"

        # Build task entry
        entry_lines = [f"- {checkbox} {display_name}"]
        if priority:
            entry_lines[0] += f" (priority: {priority})"
        if body.strip():
            for line in body.strip().split('\n'):
                if line.strip():
                    entry_lines.append(f"\t{line}")

        entry = '\n'.join(entry_lines)

        # Route to project if linked
        if relates:
            # relates can be a string or list
            if isinstance(relates, list):
                relates_key = relates[0]
            else:
                relates_key = relates
            if relates_key:
                self.project_tasks[relates_key].append(entry)
                self.stats["tasks_linked"] += 1
            else:
                # Empty relates — treat as orphan
                if done or status in ('done', 'cancelled'):
                    status_note = f" *(cancelled)*" if status == 'cancelled' else ""
                    self.weekly_tasks[week_key]["done"].append(f"- [x] {display_name}{status_note}")
                    self.stats["tasks_weekly"] += 1
                else:
                    self.open_orphan_tasks.append(entry)
                    self.stats["tasks_orphan_open"] += 1
        elif done or status in ('done', 'cancelled'):
            # Completed orphan → weekly journal
            status_note = f" *(cancelled)*" if status == 'cancelled' else ""
            self.weekly_tasks[week_key]["done"].append(f"- [x] {display_name}{status_note}")
            self.stats["tasks_weekly"] += 1
        else:
            # Open orphan → review list
            self.open_orphan_tasks.append(entry)
            self.stats["tasks_orphan_open"] += 1

    def _detect_type_from_content(self, content):
        """Detect type from content fields when filename doesn't have a type tag."""
        # Session/activity logs have "Type of session" field
        if re.search(r'\*\*Type of session\*\*', content):
            return "sessions"
        # Check for first-line hash tags
        first_line = content.strip().split('\n')[0] if content.strip() else ""
        tag_match = re.search(r'#(meeting|book|project|task|idea|video|podcast)', first_line)
        if tag_match:
            return tag_match.group(1)
        return None

    def _extract_person_from_discuss(self, content, name):
        """Try to extract a person's name from a discuss item."""
        # Look for #person or #friend tags with a name before them
        match = re.search(r'(\w[\w\s]+?)\s*#(?:person|friend)', content)
        if match:
            return match.group(1).strip()
        # Check the name/title for person references
        match = re.search(r'(\w[\w\s]+?)\s*#(?:person|friend)', name)
        if match:
            return match.group(1).strip()
        return None

    # ── Library Processing ────────────────────────────────────────────────

    def _process_library(self):
        library_root = TANA_EXPORT / "Library"
        if not library_root.exists():
            print("  WARNING: Library folder not found")
            return

        print("  Processing Library...")
        # Recursively find ALL typed files in the library tree
        self._process_library_recursive(library_root)

    def _process_library_recursive(self, folder):
        """Recursively process a Library folder, routing typed items and
        treating untyped folders as reference material."""
        for item in sorted(folder.iterdir()):
            if item.name == "README.md":
                continue

            types = extract_type_from_filename(item.name)
            name = extract_name_from_filename(item.name)
            primary_type = types[0] if types else None

            if primary_type and (NUMBERED_RE.match(primary_type) or primary_type in DROP_TYPES):
                continue

            if item.is_file() and item.suffix == '.md':
                content = item.read_text(encoding='utf-8', errors='replace')
                content = clean_content(content)
                if primary_type:
                    # If a meaningful type like 'project' is buried after a step/descriptor
                    # parenthetical, prefer it over the descriptor as the routing type
                    PRIORITY_TYPES = {"project", "meeting", "book", "person", "idea", "podcast",
                                      "video", "lesson", "task", "goal", "initiative", "area"}
                    effective_type = primary_type
                    if primary_type not in PRIORITY_TYPES and len(types) > 1:
                        for t in types[1:]:
                            if t in PRIORITY_TYPES:
                                effective_type = t
                                break
                    self._route_by_type(effective_type, name, content, "", "", types)
                else:
                    # Check if content reveals a type (e.g. sessions without filename type)
                    detected_type = self._detect_type_from_content(content)
                    if detected_type:
                        self._route_by_type(detected_type, name, content, "", "", [detected_type])
                    else:
                        content = convert_tana_links(content)
                        self.uncategorized.append((name, content))
                        self.stats["uncategorized"] += 1

            elif item.is_dir():
                # Check if the folder itself has typed children
                has_typed_children = any(
                    extract_type_from_filename(c.name)
                    for c in item.iterdir()
                    if c.name != "README.md" and c.suffix == '.md'
                )
                has_subdirs_with_typed = any(
                    c.is_dir() and c.name != "README.md"
                    for c in item.iterdir()
                )

                # Container types: these are grouping folders that hold projects/items inside
                # — create a file for the container itself, then recurse for children
                CONTAINER_TYPES = {"initiative", "area", "module", "breakdown"}

                if primary_type in CONTAINER_TYPES:
                    # Create a file for the container from its README
                    readme = item / "README.md"
                    if readme.exists():
                        container_content = readme.read_text(encoding='utf-8', errors='replace')
                        container_content = clean_content(container_content)
                        self._route_by_type(primary_type, name, container_content, "", "", types)
                    # Then recurse into children to find nested typed items
                    self._process_library_recursive(item)
                elif primary_type == "project":
                    # Project folders: create a file for the project itself (from README
                    # and direct children only), then recurse to find nested sub-projects
                    readme = item / "README.md"
                    if readme.exists():
                        proj_content = readme.read_text(encoding='utf-8', errors='replace')
                        proj_content = clean_content(proj_content)
                        self._route_by_type("project", name, proj_content, "", "", types)
                    else:
                        # No README — merge top-level content only
                        content = merge_folder_content(item)
                        content = clean_content(content)
                        self._route_by_type("project", name, content, "", "", types)
                    # Always recurse to catch nested projects (e.g. Related projects/)
                    self._process_library_recursive(item)
                elif primary_type:
                    # Typed folder — merge and route
                    content = merge_folder_content(item)
                    content = clean_content(content)
                    self._route_by_type(primary_type, name, content, "", "", types)
                elif has_typed_children or has_subdirs_with_typed:
                    # Untyped folder but has typed children — recurse into it
                    self._process_library_recursive(item)
                else:
                    # Untyped folder with no typed children — treat as reference
                    content = merge_folder_content(item)
                    content = clean_content(content)
                    content = convert_tana_links(content)
                    if name:
                        fname = sanitize_filename(name) + ".md"
                        self._write_file(PERSONAL_OUT / "Reference" / fname, content.strip() + "\n")
                        self.stats["reference_library"] += 1
                    else:
                        self.uncategorized.append((item.name, content))

    # ── Special Sections ──────────────────────────────────────────────────

    def _process_special_sections(self):
        workspace_root = TANA_EXPORT / 'Example Workspace'

        # Top of Mind
        print("  Processing Top of Mind...")
        tom = workspace_root / "Top of mind"
        if tom.exists():
            content = merge_folder_content(tom)
            content = clean_content(content)
            content = convert_tana_links(content)
            self._write_file(PERSONAL_OUT / "Personal" / "Top of Mind.md", content.strip() + "\n")
            self.stats["special_sections"] += 1

        # Back of Mind
        print("  Processing Back of Mind...")
        bom = workspace_root / "Back of mind"
        if bom.exists():
            content = merge_folder_content(bom)
            content = clean_content(content)
            content = convert_tana_links(content)
            self._write_file(PERSONAL_OUT / "Personal" / "Back of Mind.md", content.strip() + "\n")
            self.stats["special_sections"] += 1

        # Personal OS
        print("  Processing Personal OS 1.0...")
        pos = workspace_root / "Personal OS 1.0"
        if pos.exists():
            # Extract impossible list items for Bucket List
            impossible_dir = pos / "Impossible list"
            if impossible_dir.exists():
                for item in sorted(impossible_dir.iterdir()):
                    if item.name == "README.md":
                        continue
                    if item.is_file() and item.suffix == '.md':
                        content = item.read_text(encoding='utf-8', errors='replace')
                        title, done, body = extract_first_line_info(content)
                        name = extract_name_from_filename(item.name)
                        display = name if name else title
                        checkbox = "[x]" if done else "[ ]"
                        self.list_items[("_MOCs", "Bucket List.md")].append(f"- {checkbox} {display}")

            # Write Personal OS (values + session types + goals)
            full_content = merge_folder_content(pos)
            full_content = clean_content(full_content)
            full_content = convert_tana_links(full_content)
            self._write_file(PERSONAL_OUT / "Personal" / "Personal OS.md", full_content.strip() + "\n")
            self.stats["special_sections"] += 1

        # Workbench
        print("  Processing Workbench...")
        wb = workspace_root / "Workbench"
        if wb.exists():
            # Route video files to Content/Videos
            videos_dir = wb / "Current videos"
            if videos_dir.exists():
                for item in sorted(videos_dir.iterdir()):
                    if item.name == "README.md":
                        continue
                    types = extract_type_from_filename(item.name)
                    name = extract_name_from_filename(item.name)
                    if item.is_file() and item.suffix == '.md':
                        content = item.read_text(encoding='utf-8', errors='replace')
                    elif item.is_dir():
                        content = merge_folder_content(item)
                    else:
                        continue
                    content = clean_content(content)
                    metadata, body = extract_metadata(content)
                    body = convert_tana_links(body)
                    yaml = make_video_yaml(metadata)
                    fname = sanitize_filename(name) + ".md"
                    self._write_file(
                        PERSONAL_OUT / "Content" / "Videos" / fname,
                        f"{yaml}\n\n{body.strip()}\n"
                    )
                    self.stats["workbench_videos"] += 1

            # Old demo content → Reference
            demo_dir = wb / "Old demo content"
            if demo_dir.exists():
                content = merge_folder_content(demo_dir)
                content = clean_content(content)
                content = convert_tana_links(content)
                self._write_file(PERSONAL_OUT / "Reference" / "Workbench Demo.md", content.strip() + "\n")

        # Schema
        print("  Processing Schema...")
        schema = TANA_EXPORT / "Schema"
        if schema.exists():
            content = merge_folder_content(schema)
            content = clean_content(content)
            content = convert_tana_links(content)
            self._write_file(PERSONAL_OUT / "Reference" / "Schema.md", content.strip() + "\n")
            self.stats["special_sections"] += 1

        # Workspace Definition
        ws_def = workspace_root / "Workspace definition"
        if ws_def.exists():
            content = merge_folder_content(ws_def)
            content = clean_content(content)
            content = convert_tana_links(content)
            self._write_file(PERSONAL_OUT / "Reference" / "Workspace Definition.md", content.strip() + "\n")
            self.stats["special_sections"] += 1

        # Inbox
        inbox = TANA_EXPORT / "Inbox"
        if inbox.exists():
            for item in sorted(inbox.iterdir()):
                if item.name == "README.md":
                    continue
                if item.is_file() and item.suffix == '.md':
                    content = item.read_text(encoding='utf-8', errors='replace')
                    content = clean_content(content)
                    types = extract_type_from_filename(item.name)
                    name = extract_name_from_filename(item.name)
                    primary_type = types[0] if types else None
                    if primary_type:
                        self._route_by_type(primary_type, name, content, "", "", types)
                    else:
                        content = convert_tana_links(content)
                        self.uncategorized.append((name, content))

    # ── Output Writers ────────────────────────────────────────────────────

    def _write_projects(self):
        """Write all project files with appended tasks and chunks."""
        print("  Writing projects...")
        for proj_name, proj_data in self.projects.items():
            vault_out = WORK_OUT if proj_data["vault"] == "work" else PERSONAL_OUT
            fname = sanitize_filename(proj_name) + ".md"

            parts = [proj_data["yaml"], "", proj_data["content"].strip()]

            # Append linked tasks
            tasks = self._find_project_tasks(proj_name)
            if tasks:
                parts.append("\n\n## Tasks\n")
                parts.extend(tasks)

            # Append linked chunks
            chunks = self._find_project_chunks(proj_name)
            if chunks:
                parts.append("\n\n## Chunks\n")
                parts.extend(chunks)

            self._write_file(vault_out / "Projects" / fname, '\n'.join(parts) + "\n")

    def _write_areas(self):
        """Write all area files."""
        print("  Writing areas...")
        for area_name, area_data in self.areas.items():
            vault_out = WORK_OUT if area_data["vault"] == "work" else PERSONAL_OUT
            fname = sanitize_filename(area_name) + ".md"

            parts = [area_data["yaml"], "", area_data["content"].strip()]

            # Append linked tasks
            tasks = self._find_project_tasks(area_name)
            if tasks:
                parts.append("\n\n## Tasks\n")
                parts.extend(tasks)

            self._write_file(vault_out / "Areas" / fname, '\n'.join(parts) + "\n")

    def _write_initiatives(self):
        """Write all initiative files."""
        print("  Writing initiatives...")
        for init_name, init_data in self.initiatives.items():
            vault_out = WORK_OUT if init_data["vault"] == "work" else PERSONAL_OUT
            fname = sanitize_filename(init_name) + ".md"

            parts = [init_data["yaml"], "", init_data["content"].strip()]

            # Append linked tasks
            tasks = self._find_project_tasks(init_name)
            if tasks:
                parts.append("\n\n## Tasks\n")
                parts.extend(tasks)

            # Append linked chunks
            chunks = self._find_project_chunks(init_name)
            if chunks:
                parts.append("\n\n## Chunks\n")
                parts.extend(chunks)

            self._write_file(vault_out / "Initiatives" / fname, '\n'.join(parts) + "\n")

    def _find_project_tasks(self, project_name):
        """Find tasks that relate to a project (fuzzy matching)."""
        tasks = []
        pname_lower = project_name.lower()
        for key, items in self.project_tasks.items():
            if key.lower() in pname_lower or pname_lower in key.lower():
                tasks.extend(items)
        return tasks

    def _find_project_chunks(self, project_name):
        """Find chunks that relate to a project (fuzzy matching)."""
        chunks = []
        pname_lower = project_name.lower()
        for key, items in self.project_chunks.items():
            if key.lower() in pname_lower or pname_lower in key.lower():
                chunks.extend(items)
        return chunks

    def _write_list_files(self):
        """Write aggregated list files."""
        print("  Writing list files...")
        for (folder, filename), items in sorted(self.list_items.items()):
            if not items:
                continue
            content = '\n'.join(items)
            # Route tracking-oriented lists to the Tracking vault
            if folder == "_TRACKING_":
                self._write_file(TRACKING_OUT / filename, content + "\n")
            else:
                self._write_file(PERSONAL_OUT / folder / filename, content + "\n")
            self.stats[f"lists_{filename}"] += 1

        # Append discuss items to people files
        print("  Appending discuss items to people...")
        for person, items in self.people_discuss.items():
            if person == "_unlinked":
                # Write unlinked discuss items to a separate file
                content = "## Unlinked Discussion Points\n\n" + '\n'.join(items) + "\n"
                self._append_file(PERSONAL_OUT / "People" / "_Discussion Points.md", content)
                continue
            fname = sanitize_filename(person) + ".md"
            person_file = PERSONAL_OUT / "People" / fname
            discuss_content = "\n\n## Discussion Points\n\n" + '\n'.join(items) + "\n"
            self._append_file(person_file, discuss_content)

    def _write_weekly_journals(self):
        """Write weekly journal files with task summaries."""
        print("  Writing weekly journals...")
        for week_key, tasks in sorted(self.weekly_tasks.items()):
            if not tasks["done"] and not tasks["open"]:
                continue
            # Parse week key like "2024_W20"
            match = re.match(r'(\d{4})_W(\d+)', week_key)
            if not match:
                continue
            year = match.group(1)
            week = int(match.group(2))

            yaml = f"---\nweek: {week}\nyear: {year}\n---\n"
            parts = [yaml]

            if tasks["done"]:
                parts.append("\n## Completed Tasks\n")
                parts.extend(tasks["done"])

            if tasks["open"]:
                parts.append("\n\n## Open Tasks\n")
                parts.extend(tasks["open"])

            fname = f"{year}_W{week:02d}.md"
            self._write_file(
                TRACKING_OUT / "Weekly" / fname,
                '\n'.join(parts) + "\n"
            )
            self.stats["weekly_journals"] += 1

    def _write_open_tasks(self):
        """Write the orphan open tasks review list."""
        if not self.open_orphan_tasks:
            return
        print("  Writing open tasks review list...")
        content = "# Open Tasks (Review)\n\n"
        content += "These tasks were not linked to any project and are still open.\n\n"
        content += '\n'.join(self.open_orphan_tasks) + "\n"
        self._write_file(TRACKING_OUT / "Open Tasks.md", content)

    def _write_uncategorized(self):
        """Triage uncategorized items by pattern:
        - Course modules (numbered like '1.' or '2.2.2') → Lessons folder
        - Short hash-like names with no content → discard
        - Everything else → single Inbox.md file
        """
        if not self.uncategorized:
            return
        print(f"  Triaging {len(self.uncategorized)} uncategorized items...")

        lesson_pattern = re.compile(r'^\d+(\.\d+)*\.?\s+\S')
        hash_pattern = re.compile(r'^[A-Za-z0-9_\-]{10,}$')
        inbox_entries = []
        lessons_count = 0
        discarded_count = 0

        for name, content in self.uncategorized:
            if not name:
                name = "untitled"
            clean_name = name.strip()
            # Defensive: ensure Tana links are converted
            content = convert_tana_links(content)
            body = content.strip()

            # Route numbered course modules to Lessons
            if lesson_pattern.match(clean_name):
                fname = sanitize_filename(clean_name) + ".md"
                yaml = "---\ntype: \"[[Lesson]]\"\n---\n\n"
                self._write_file(PERSONAL_OUT / "Content" / "Lessons" / fname,
                                 yaml + f"# {clean_name}\n\n{body}\n")
                lessons_count += 1
                continue

            # Discard hash-like orphan nodes with no meaningful content
            if hash_pattern.match(clean_name):
                # Keep only if body has substantive text
                body_text = re.sub(r'^#.*$', '', body, flags=re.MULTILINE).strip()
                if len(body_text) < 20:
                    discarded_count += 1
                    continue

            # Everything else → Inbox.md
            entry = f"## {clean_name}\n\n{body}\n"
            inbox_entries.append(entry)

        if lessons_count:
            self.stats["uncategorized_to_lessons"] = lessons_count
        if discarded_count:
            self.stats["uncategorized_discarded"] = discarded_count
        if inbox_entries:
            print(f"  Writing {len(inbox_entries)} entries to Inbox.md...")
            inbox_content = ("---\ntype: \"[[Inbox]]\"\n---\n\n"
                             "# Inbox\n\n"
                             "Uncategorised notes from the Tana export. Review and re-file as needed.\n\n"
                             + "\n\n---\n\n".join(inbox_entries) + "\n")
            self._write_file(PERSONAL_OUT / "Inbox.md", inbox_content)
            self.stats["uncategorized_to_inbox"] = len(inbox_entries)

    def _merge_book_reviews(self):
        """Merge book review content into matching book files."""
        for review_key, review_data in self.book_reviews.items():
            # Try to find matching book file
            matched = False
            for book_key, book_name in self.books.items():
                if review_key in book_key or book_key in review_key:
                    # Append review to book file
                    book_file = PERSONAL_OUT / "Content" / "Books" / (sanitize_filename(book_name) + ".md")
                    if book_file.exists():
                        review_section = f"\n\n## Review\n\n{review_data['content'].strip()}\n"
                        if review_data.get('link'):
                            review_section += f"\n[Purchase link]({review_data['link']})\n"
                        self._append_file(book_file, review_section)
                        matched = True
                        self.stats["book_reviews_merged"] += 1
                        break

            if not matched:
                # Write as standalone in Books
                fname = sanitize_filename(review_data['name']) + " (Review).md"
                content = f"# {review_data['name']} - Review\n\n{review_data['content'].strip()}\n"
                self._write_file(PERSONAL_OUT / "Content" / "Books" / fname, content)

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

    def _is_work_project(self, name):
        """Check if a project name matches the work projects list."""
        for wp in WORK_PROJECTS:
            if wp.lower() in name.lower() or name.lower() in wp.lower():
                return True
        # Also check for Example Organisation-related content
        if False:  # Installation-specific employer shortcut removed; define a reviewed mapping.
            return True
        return False

    def _is_work_area(self, name):
        """Check if an area is work-related."""
        # Check if it matches a known work project
        if self._is_work_project(name):
            return True
        # Specific work areas
        WORK_AREAS = {"accounting", "finances", "business crm", "consulting",
                      "business systems enablement"}
        return name.lower() in WORK_AREAS or any(wa in name.lower() for wa in WORK_AREAS)

    def _is_work_initiative(self, name):
        """Check if an initiative is work-related."""
        if self._is_work_project(name):
            return True
        WORK_INITIATIVES = set()  # Configure only from a reviewed fictional test mapping.
        return any(wi in name.lower() for wi in WORK_INITIATIVES)

    def _indent_content(self, content, level=1):
        """Indent content by a level."""
        prefix = '\t' * level
        lines = content.split('\n')
        return '\n'.join(prefix + line if line.strip() else line for line in lines)

    def _write_file(self, path, content):
        """Write content to a file, creating parent dirs if needed.
        If the file already exists:
        - Skip if content is already present (dedup)
        - Otherwise append with YAML stripped from the new content
        """
        path.parent.mkdir(parents=True, exist_ok=True)
        if path.exists():
            existing = path.read_text(encoding='utf-8', errors='replace')
            new_stripped = content.strip()
            existing_stripped = existing.strip()
            # Skip if content is already present (exact duplicate or subset)
            if new_stripped in existing_stripped or existing_stripped in new_stripped:
                return
            # Strip YAML frontmatter from new content before appending
            new_body = self._strip_yaml_frontmatter(content)
            if not new_body.strip():
                return  # Nothing useful to append
            # Check the body isn't already present either
            if new_body.strip() in existing_stripped:
                return
            content = existing.rstrip() + "\n\n---\n\n" + new_body.strip() + "\n"
        path.write_text(content, encoding='utf-8')

    @staticmethod
    def _strip_yaml_frontmatter(content):
        """Remove YAML frontmatter (--- ... ---) from content."""
        lines = content.split('\n')
        if lines and lines[0].strip() == '---':
            # Find closing ---
            for i in range(1, len(lines)):
                if lines[i].strip() == '---':
                    return '\n'.join(lines[i+1:])
        return content

    def _append_file(self, path, content):
        """Append content to an existing file or create it."""
        path.parent.mkdir(parents=True, exist_ok=True)
        if path.exists():
            existing = path.read_text(encoding='utf-8', errors='replace')
            content = existing.rstrip() + "\n" + content
        path.write_text(content, encoding='utf-8')


# ─── Entry Point ─────────────────────────────────────────────────────────────

if __name__ == "__main__":
    migrator = TanaMigrator()
    migrator.run()
