# 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 vault to Obsidian format (v3).

Handles:
- YAML frontmatter conversion (properties → ---/--- blocks)
- Block reference migration (id:: → ^short_id, ((uuid)) → ![[File#^id]])
- Namespace handling (folders vs tag-flattening)
- Filename sanitization (%3F, %3A, %22, %7C)
- Wikilink updates to match new filenames
- Parent index page generation for folder namespaces
"""

import re
import sys
import os
import shutil
from pathlib import Path
from urllib.parse import unquote

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

MONTHS = {
    'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
    'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12
}

SKIP_PROPS = {'title', 'collapsed', 'filters'}

RENAME = {
    'instance-of': 'output',
    'date_finished': 'date-finished',
    'recommended_by': 'recommended-by',
    'date-synced': 'date-synced',
    'date-published': 'date-published',
    'tags': 'themes',
    'alias': 'aliases',
}

SCALAR_PROPS = {'rating', 'link'}

# Namespaces that get flattened with underscores and a tag in frontmatter
# (spaces in these names become hyphens in the tag)
TAG_NAMESPACES = {
    'spectrums',
    'times in my life',
    'times I felt or experienced',
    'state',
}

# ─── Filename sanitization ──────────────────────────────────────────

def sanitize_filename(name: str) -> str:
    """
    Clean up a filename:
    - Decode %2F → / (handled separately by namespace logic)
    - %3F (?) → removed
    - %3A (:) → " -"
    - %22 (") → "'"
    - %7C (|) → "-"
    """
    # First decode %2F to / so namespace logic can split on it
    name = name.replace('%2F', '/')
    # Now handle the other special characters BEFORE general URL decoding
    name = name.replace('%3F', '')
    name = name.replace('%3A', ' -')
    name = name.replace('%22', "'")
    name = name.replace('%7C', '-')
    # Decode any remaining percent-encoded chars
    # (but we've already handled the problematic ones above)
    return name


def logseq_name_to_parts(filename: str) -> tuple[list[str], str]:
    """
    Given a Logseq filename like "BJJ%2Fguard%2Fhalf.md",
    return (namespace_parts, leaf_name).
    E.g. (['BJJ', 'guard'], 'half')
    For non-namespaced files: ([], 'some file')
    """
    stem = filename
    if stem.endswith('.md'):
        stem = stem[:-3]
    sanitized = sanitize_filename(stem)
    parts = sanitized.split('/')
    if len(parts) == 1:
        return [], parts[0]
    return parts[:-1], parts[-1]


# ─── Namespace resolution ───────────────────────────────────────────

def is_tag_namespace(ns_parts: list[str]) -> bool:
    """Check if the top-level namespace should be flattened with tags."""
    if not ns_parts:
        return False
    # Match against TAG_NAMESPACES (case-insensitive)
    top = ns_parts[0].lower()
    return any(top == tn.lower() for tn in TAG_NAMESPACES)


def resolve_output_path(ns_parts: list[str], leaf: str) -> str:
    """
    Determine the output path for a file.
    - Tag namespaces: flatten → "namespace_leaf.md" (no folder)
    - Folder namespaces: "TopNS/TopNS_sub_leaf.md" (underscore name in top folder)
    - No namespace: "leaf.md"
    """
    if not ns_parts:
        return f"{leaf}.md"

    if is_tag_namespace(ns_parts):
        # Flatten: join all parts with underscore, no folder
        flat_parts = [re.sub(r'\s+', '-', p) for p in ns_parts]
        return f"{'_'.join(flat_parts)}_{leaf}.md"
    else:
        # Folder namespace: underscore-joined filename in top-level folder
        top_folder = ns_parts[0]
        all_parts = ns_parts + [leaf]
        flat_name = '_'.join(all_parts)
        return f"{top_folder}/{flat_name}.md"


def resolve_link_name(ns_parts: list[str], leaf: str) -> str:
    """
    Determine how this page should be referenced in [[wikilinks]].
    ALL namespaces use underscore format for wikilinks.
    """
    if not ns_parts:
        return leaf

    if is_tag_namespace(ns_parts):
        flat_parts = [re.sub(r'\s+', '-', p) for p in ns_parts]
        return '_'.join(flat_parts) + '_' + leaf
    else:
        # Folder namespaces also use underscore in links
        return '_'.join(ns_parts + [leaf])


def get_tag_for_namespace(ns_parts: list[str]) -> str | None:
    """
    For tag namespaces, return the tag string to add to frontmatter.
    E.g. ['times in my life'] → 'times-in-my-life'
    Returns None for non-tag namespaces.
    """
    if not ns_parts or not is_tag_namespace(ns_parts):
        return None
    return '/'.join(re.sub(r'\s+', '-', p) for p in ns_parts)


# ─── Name mapping ──────────────────────────────────────────────────

def build_name_mapping(input_dir: Path) -> dict[str, str]:
    '\n    Build a mapping of old Logseq page names → new Obsidian page names.\n    Used to update wikilinks in body text.\n\n    Key: Logseq name (e.g. "topics/Example Person A")\n    Value: Obsidian name (e.g. "topics/Example Person A" for folders,\n           or "spectrums_warmth" for tag namespaces)\n    Also includes sanitized versions for special characters.\n    '
    name_map = {}

    for fpath in sorted(input_dir.glob('*.md')):
        old_stem = fpath.stem  # URL-encoded stem
        sanitized = sanitize_filename(old_stem)

        # If name changed due to sanitization, add mapping
        if sanitized != old_stem:
            # Map the decoded version of the old name
            decoded_old = unquote(old_stem)
            if decoded_old != sanitized:
                name_map[decoded_old] = sanitized

        # Handle namespaces
        ns_parts, leaf = logseq_name_to_parts(fpath.name)
        if ns_parts:
            old_logseq_name = '/'.join(ns_parts) + '/' + leaf
            new_link_name = resolve_link_name(ns_parts, leaf)
            if old_logseq_name != new_link_name:
                name_map[old_logseq_name] = new_link_name

            # Also map the URL-encoded version
            old_encoded = old_stem.replace('%2F', '/')
            if old_encoded != old_logseq_name and old_encoded not in name_map:
                name_map[old_encoded] = new_link_name

    return name_map


# ─── Wikilink updating ─────────────────────────────────────────────

def update_wikilinks_in_line(line: str, name_map: dict[str, str]) -> str:
    """
    Update [[wikilinks]] in a line based on the name mapping.
    Does NOT touch #hashtag references — those stay as nested tags.
    Also does NOT touch wikilinks inside YAML frontmatter values.
    """
    def replace_link(m):
        full_match = m.group(0)
        inner = m.group(1)

        # Check if this is preceded by # (hashtag) — don't touch
        start = m.start()
        if start > 0 and line[start - 1] == '#':
            return full_match

        # Check for alias: [[name|alias]]
        if '|' in inner:
            name_part, alias = inner.split('|', 1)
            name_part = name_part.strip()
            if name_part in name_map:
                return f"[[{name_map[name_part]}|{alias}]]"
            return full_match

        if inner in name_map:
            return f"[[{name_map[inner]}]]"
        return full_match

    return re.sub(r'\[\[([^\]]+)\]\]', replace_link, line)


# ─── Index page generation ──────────────────────────────────────────

def create_index_pages(input_dir: Path, output_dir: Path):
    """
    For folder namespaces, create parent index pages that link to children.
    E.g. BJJ.md with links to [[BJJ_guard_half]], [[BJJ_mount]], etc.
    Uses underscore link format.
    """
    # Collect all namespace hierarchies
    ns_children: dict[str, list[str]] = {}  # "BJJ" → ["BJJ_guard_half", ...]

    for fpath in sorted(input_dir.glob('*.md')):
        ns_parts, leaf = logseq_name_to_parts(fpath.name)
        if not ns_parts or is_tag_namespace(ns_parts):
            continue

        top = ns_parts[0]
        # Link name uses underscore format
        link_name = '_'.join(ns_parts + [leaf])

        if top not in ns_children:
            ns_children[top] = []
        ns_children[top].append(link_name)

    # Write or append to index pages
    for top, children in sorted(ns_children.items()):
        index_path = output_dir / f"{top}.md"
        index_path.parent.mkdir(parents=True, exist_ok=True)

        # Build the links block
        links_block = '\n'.join(f"- [[{child}]]" for child in sorted(children))

        if index_path.exists():
            # Parent page already exists (was converted from source file)
            # Append child links below existing content
            with open(index_path, 'r', encoding='utf-8') as f:
                existing = f.read()
            with open(index_path, 'w', encoding='utf-8') as f:
                f.write(existing.rstrip('\n'))
                f.write('\n\n')
                f.write(links_block)
                f.write('\n')
            print(f"  APPEND: {top}.md (+{len(children)} links)")
        else:
            # No source file — create a fresh index page
            with open(index_path, 'w', encoding='utf-8') as f:
                f.write(f"# {top}\n\n")
                f.write(links_block)
                f.write('\n')
            print(f"  INDEX: {top}.md ({len(children)} children)")


# ─── Date parsing ───────────────────────────────────────────────────

def parse_date(value: str) -> str | None:
    cleaned = value.strip().strip('[').strip(']')
    if re.match(r'^\d{4}$', cleaned):
        return cleaned
    m = re.match(r'([A-Za-z]+)\s+(\d+)(?:st|nd|rd|th)?,?\s*(\d{4})', cleaned)
    if m:
        month_str, day_str, year_str = m.groups()
        month_num = MONTHS.get(month_str.lower()[:3])
        if month_num:
            return f"{year_str}_{month_num:02d}_{int(day_str):02d}"
    return None


def is_date_property(key: str) -> bool:
    return 'date' in key.lower() or key in ('year', 'published', 'start', 'end')


def convert_date_in_wikilink(value: str) -> str:
    m = re.match(r'^\[\[(.+)\]\]$', value.strip())
    if m:
        inner = m.group(1)
        converted = parse_date(inner)
        if converted:
            return f"[[{converted}]]"
    return value


# ─── Value parsing ──────────────────────────────────────────────────

def split_multi_values(value: str) -> list[str]:
    items = []
    wikilinks = re.findall(r'\[\[([^\]]+)\]\]', value)
    if wikilinks:
        return [f"[[{w.strip()}]]" for w in wikilinks]

    bracket_hashtags = re.findall(r'#\[\[([^\]]+)\]\]', value)
    if bracket_hashtags:
        for tag in bracket_hashtags:
            items.append(f"[[{tag.strip()}]]")
        return items

    # Check for hashtag-separated values (e.g. "#Buddhism #Sent to Logseq")
    if '#' in value:
        parts = re.split(r'\s*#', value)
        for part in parts:
            part = part.strip()
            if part:
                tag = re.sub(r'\s+', '-', part)
                items.append(f"[[{tag}]]")
        if items:
            return items

    # Check for comma-separated plain text values (e.g. "advertising, ebay, ineffectiveness")
    if ',' in value:
        parts = [p.strip() for p in value.split(',')]
        for part in parts:
            if part:
                items.append(f"[[{part}]]")
        if items:
            return items

    cleaned = value.strip().rstrip(',').strip()
    if cleaned:
        return [cleaned]
    return []


def format_yaml_value(key: str, values: list[str]) -> str:
    if not values:
        return f"{key}:"
    if key in SCALAR_PROPS:
        val = values[0]
        m = re.match(r'^\[\[(.+)\]\]$', val)
        if m:
            val = m.group(1)
        return f"{key}: {val}"
    lines = [f"{key}:"]
    for v in values:
        if v.startswith("[["):
            lines.append(f'  - "{v}"')
        else:
            lines.append(f'  - {v}')
    return '\n'.join(lines)


def capitalize_type_value(value: str) -> str:
    m = re.match(r'^\[\[(.+)\]\]$', value)
    if m:
        inner = m.group(1)
        return f"[[{inner[0].upper() + inner[1:]}]]"
    return value


# ─── Block reference handling ───────────────────────────────────────

def shorten_uuid(uuid: str, length: int = 8) -> str:
    hex_only = uuid.replace('-', '')
    return hex_only[:length]


def build_block_id_map(input_dir: Path) -> tuple[dict[str, str], dict[str, str]]:
    """
    Returns (uuid_to_file, uuid_to_short).
    uuid_to_file maps block UUID → sanitized filename (without .md).
    """
    uuid_to_file = {}
    id_pattern = re.compile(r'id::\s*([a-f0-9-]{36})')

    for fpath in sorted(input_dir.glob('*.md')):
        # Use sanitized name for the file reference
        ns_parts, leaf = logseq_name_to_parts(fpath.name)
        link_name = resolve_link_name(ns_parts, leaf)

        with open(fpath, 'r', encoding='utf-8') as f:
            for line in f:
                m = id_pattern.search(line)
                if m:
                    uuid_to_file[m.group(1)] = link_name

    uuid_to_short = {}
    short_to_uuid = {}
    for uuid in uuid_to_file:
        length = 8
        short = shorten_uuid(uuid, length)
        hex_only = uuid.replace('-', '')
        while short in short_to_uuid and short_to_uuid[short] != uuid:
            length += 1
            if length > len(hex_only):
                short = hex_only
                break
            short = hex_only[:length]
        uuid_to_short[uuid] = short
        short_to_uuid[short] = uuid

    return uuid_to_file, uuid_to_short


def convert_body_block_refs(body_lines: list[str], block_id_map: dict[str, str],
                            uuid_to_short: dict[str, str]) -> list[str]:
    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(body_lines):
        line = body_lines[i]
        id_match = id_line_pattern.match(line)
        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(body_lines):
                next_line = body_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


# ─── File conversion ────────────────────────────────────────────────

def convert_file(input_path: Path, output_path: Path,
                  block_id_map: dict[str, str] | None = None,
                  uuid_to_short: dict[str, str] | None = None,
                  name_map: dict[str, str] | None = None,
                  namespace_tag: str | None = None):
    if block_id_map is None:
        block_id_map = {}
    if uuid_to_short is None:
        uuid_to_short = {}
    if name_map is None:
        name_map = {}

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

    properties = []
    body_start = 0

    prop_pattern = re.compile(r'^([a-zA-Z_-]+)::\s*(.*)')
    for i, line in enumerate(lines):
        m = prop_pattern.match(line)
        if m:
            key = m.group(1).strip()
            value = m.group(2).strip().rstrip(',').strip()
            properties.append((key, value))
            body_start = i + 1
        elif line.strip() == '':
            if properties:
                body_start = i
                break
        else:
            body_start = i
            break

    if not properties:
        body = convert_body_block_refs(lines, block_id_map, uuid_to_short)
        body = [update_wikilinks_in_line(l, name_map) for l in body]
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            for line in body:
                f.write(line)
        return

    yaml_lines = ['---']

    for key, raw_value in properties:
        norm_key = key.lower()
        if norm_key in 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'
        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))

    # Add namespace tag if this file is from a tag namespace
    if namespace_tag:
        has_themes = any(
            l.startswith('themes:') for l in yaml_lines
        )
        if has_themes:
            for idx, l in enumerate(yaml_lines):
                if l.startswith('themes:'):
                    insert_at = idx + 1
                    while insert_at < len(yaml_lines) and yaml_lines[insert_at].startswith('  - '):
                        insert_at += 1
                    yaml_lines.insert(insert_at, f'  - "[[{namespace_tag}]]"')
                    break
        else:
            yaml_lines.append(f'themes:\n  - "[[{namespace_tag}]]"')

    yaml_lines.append('---')

    body = convert_body_block_refs(lines[body_start:], block_id_map, uuid_to_short)
    body = [update_wikilinks_in_line(l, name_map) for l in body]
    output_path.parent.mkdir(parents=True, exist_ok=True)

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(yaml_lines))
        f.write('\n')
        for line in body:
            f.write(line)


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

def convert_folder(input_dir: Path, output_dir: Path,
                    file_list: list[str] | None = None):
    output_dir.mkdir(parents=True, exist_ok=True)

    # Build all maps
    print("Building block ID map...")
    block_id_map, uuid_to_short = build_block_id_map(input_dir)
    print(f"  Found {len(block_id_map)} block IDs")
    collisions = len([s for s in uuid_to_short.values() if len(s) > 8])
    if collisions:
        print(f"  ({collisions} IDs extended beyond 8 chars)")

    print("Building name mapping...")
    name_map = build_name_mapping(input_dir)
    print(f"  {len(name_map)} names will be updated")
    print()

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

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

        ns_parts, leaf = logseq_name_to_parts(fpath.name)
        out_rel = resolve_output_path(ns_parts, leaf)
        out_path = output_dir / out_rel

        # Determine if we need to add a namespace tag
        namespace_tag = get_tag_for_namespace(ns_parts)

        convert_file(fpath, out_path, block_id_map, uuid_to_short,
                      name_map, namespace_tag)
        converted += 1

        # Show what happened
        if ns_parts:
            if is_tag_namespace(ns_parts):
                print(f"  TAG: {fpath.name} → {out_rel}")
            else:
                print(f"  DIR: {fpath.name} → {out_rel}")
        else:
            print(f"   OK: {out_rel}")

    # Create index pages for folder namespaces
    print("\nCreating index pages...")
    create_index_pages(input_dir, output_dir)

    print(f"\nConverted {converted} files → {output_dir}")


# ─── 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')

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

    convert_folder(input_dir, output_dir, SAMPLE_FILES)
