#!/usr/bin/env python3
# === StraightArc Technologies Open Toolset : banner & disclaimer =============
def _sta_accept():
    import sys, os
    line = "=" * 68
    print(line)
    print("               StraightArc Technologies Open Toolset")
    print(line)
    print('DISCLAIMER: This tool is provided on an "AS IS" basis. StraightArc')
    print("Technologies or any of its associates shall not be responsible for")
    print("the consequences of its use. Always operate on a COPY of the media,")
    print("never the original evidence.")
    print(line)
    if os.environ.get("STRAIGHTARC_ACCEPT") == "1":
        return
    if not sys.stdin.isatty():
        sys.exit("Non-interactive run: set STRAIGHTARC_ACCEPT=1 to proceed.")
    try:
        ans = input("Type 'accept' to acknowledge and continue: ").strip().lower()
    except (EOFError, KeyboardInterrupt):
        sys.exit("\nDisclaimer not accepted. Exiting.")
    if ans not in ("accept", "y", "yes"):
        sys.exit("Disclaimer not accepted. Exiting.")
_sta_accept()
# ============================================================================

"""Rebuild original E:\ folder tree from the flat by-type recovered files (move, not copy)."""
import os, re, json, glob
ROOT="/mnt/d/MS/quickheal_recovered"
TREE="/mnt/d/MS/recovered_tree"
pathmap=json.load(open("pathmap.json"))
def winpath_to_rel(p):
    # "E:\22\UW\...\file.xls" -> "22/UW/.../file.xls"  (drop drive)
    p=re.sub(r'^[A-Za-z]:\\', '', p)
    return p.replace('\\','/')
def safe(seg): return re.sub(r'[<>:"|?*\x00-\x1f]','_',seg)
placed=uniq=multi=unmatched=0
manifest=open(os.path.join(TREE,"_MULTI_LOCATION_FILES.txt") if os.path.isdir(TREE) else "/dev/null","w") if False else None
os.makedirs(TREE, exist_ok=True)
manifest=open(os.path.join(TREE,"_MULTI_LOCATION_FILES.txt"),"w")
for typ in ("xls","xlsx","doc","docx","pdf","ppt","pptx","rtf","txt","eml","odt","ods"):
    d=os.path.join(ROOT,typ)
    if not os.path.isdir(d): continue
    for f in glob.glob(os.path.join(d,"*")):
        fn=os.path.basename(f)
        base=re.sub(r'__v\d+(\.[^.]+)$', r'\1', fn)   # lookup key ignores version suffix
        cands=pathmap.get(base.lower())
        if not cands:
            dst_dir=os.path.join(TREE,"_unmatched",typ); unmatched+=1
        else:
            cands=sorted(cands, key=len)  # shortest = primary location
            rel=winpath_to_rel(cands[0])
            dst_dir=os.path.join(TREE, os.path.dirname("/".join(safe(s) for s in rel.split("/"))))
            if len(cands)==1: uniq+=1
            else:
                multi+=1
                manifest.write(f"{fn}\n" + "".join(f"    {c}\n" for c in cands))
        os.makedirs(dst_dir, exist_ok=True)
        dst=os.path.join(dst_dir, fn)
        if os.path.exists(dst):
            stem,ext=os.path.splitext(fn); dst=os.path.join(dst_dir, f"{stem}_dup{ext}")
        try: os.rename(f, dst); placed+=1
        except Exception as e:
            pass
manifest.close()
print(f"files placed into tree: {placed:,}")
print(f"  uniquely-located: {uniq:,}")
print(f"  multi-location (primary folder used; others in _MULTI_LOCATION_FILES.txt): {multi:,}")
print(f"  unmatched (-> _unmatched/): {unmatched:,}")
print(f"tree root: {TREE}")


# ============================================================================
# DISCLAIMER
# This script is provided on an "AS IS" basis. StraightArc Technologies or any
# of its associates shall not be responsible for the consequences of its use.
#
# A Contribution from StraightArc Technologies (info@straightarc.com)
# ============================================================================
