# 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
"\nmerge_to_vault.py\n-----------------\nHistorical illustration of merging the Tana migration output into your existing ExampleVault vault.\n\nRules:\n  - NEVER overwrites existing files in the vault\n  - Only copies files that don't already exist at the destination\n  - Certain folders are skipped entirely (People, _Tracking, _MOCs) because\n    they're already well-populated in the vault\n  - Produces a detailed report of what was copied and what was skipped\n\nRun:\n    python3 merge_to_vault.py [--dry-run]\n\nWith --dry-run it only prints what it *would* do without touching anything.\n"

import shutil
import sys
from pathlib import Path

# ── Paths ────────────────────────────────────────────────────────────────────
MIGRATION_PERSONAL = Path('CONFIGURE_REVIEWED_COPY_PATH')
MIGRATION_WORK     = Path('CONFIGURE_REVIEWED_COPY_PATH')
VAULT              = Path('CONFIGURE_REVIEWED_COPY_PATH')
WORK_VAULT         = VAULT / "Work"  # will be created if it doesn't exist

DRY_RUN = "--dry-run" in sys.argv

# ── Skip rules ───────────────────────────────────────────────────────────────
# These are relative paths inside Personal/ that we should NOT copy because
# the vault version is already curated and more up-to-date.
SKIP_PERSONAL_SUBDIRS = set()  # Configure only from a reviewed fictional test mapping.

# ── Helpers ──────────────────────────────────────────────────────────────────
copied = []
skipped = []
errors = []

def copy_file(src: Path, dst: Path):
    if dst.exists():
        skipped.append(str(dst.relative_to(VAULT)))
        return
    if DRY_RUN:
        copied.append(f"[DRY RUN] {dst.relative_to(VAULT)}")
        return
    dst.parent.mkdir(parents=True, exist_ok=True)
    try:
        shutil.copy2(src, dst)
        copied.append(str(dst.relative_to(VAULT)))
    except Exception as e:
        errors.append(f"ERROR copying {src.name}: {e}")


def merge_dir(src_dir: Path, dst_dir: Path, skip_subdirs: set = None):
    """Recursively copy src_dir into dst_dir, skipping existing files."""
    if not src_dir.exists():
        return
    skip_subdirs = skip_subdirs or set()

    for item in sorted(src_dir.iterdir()):
        if item.name in skip_subdirs:
            print(f"  SKIPPING folder: {item.name} (already in vault)")
            continue

        dst = dst_dir / item.name

        if item.is_file():
            copy_file(item, dst)
        elif item.is_dir():
            merge_dir(item, dst)


# ── Main ─────────────────────────────────────────────────────────────────────
def main():
    mode = "DRY RUN — no files will be written" if DRY_RUN else "LIVE — files will be copied"
    print(f"\n{'='*60}")
    print(f"Tana → Obsidian_Personal Merge")
    print(f"Mode: {mode}")
    print(f"{'='*60}\n")

    # 1. Merge Personal/ → Vault/ (skipping People, _Tracking, etc.)
    print("[1/2] Merging Personal vault...")
    merge_dir(MIGRATION_PERSONAL, VAULT, skip_subdirs=SKIP_PERSONAL_SUBDIRS)

    # 2. Work vault — left in place for manual copy to separate Work vault
    print("\n[2/2] Work vault — skipped.")
    print(f"      Your Work files are ready at:")
    print(f"      Tana to Obsidian Migration/Work/")
    print(f"      Copy that folder into your Work vault manually when ready.")

    # ── Report ───────────────────────────────────────────────────────────────
    print(f"\n{'='*60}")
    print(f"Merge Complete")
    print(f"{'='*60}")
    print(f"  Files copied:  {len(copied)}")
    print(f"  Files skipped (already in vault): {len(skipped)}")
    if errors:
        print(f"  Errors: {len(errors)}")
        for e in errors:
            print(f"    {e}")

    # Write a log file
    log_path = Path('CONFIGURE_REVIEWED_COPY_PATH')
    with open(log_path, "w") as f:
        f.write(f"Merge log — {'DRY RUN' if DRY_RUN else 'LIVE'}\n\n")
        f.write(f"COPIED ({len(copied)} files):\n")
        for c in copied:
            f.write(f"  + {c}\n")
        f.write(f"\nSKIPPED ({len(skipped)} files — already in vault):\n")
        for s in skipped[:50]:  # cap at 50 to avoid giant log
            f.write(f"  ~ {s}\n")
        if len(skipped) > 50:
            f.write(f"  ... and {len(skipped) - 50} more\n")
        if errors:
            f.write(f"\nERRORS:\n")
            for e in errors:
                f.write(f"  ! {e}\n")

    print(f"\nFull log written to: merge_log.txt")

    if DRY_RUN:
        print("\nRun without --dry-run to actually copy the files.")


if __name__ == "__main__":
    main()
