#!/usr/bin/env python3
import sys, os
from src import startFinderConsole
from abstract_gui.QT6 import startConsole
from abstract_gui.QT6 import SharedStateBus

def setup_logger():
    """
    Redirects stdout and stderr to a timestamped log file.
    Keeps the latest run at /tmp/abstract_finder_console.log
    """
    log_dir = "/tmp"
    os.makedirs(log_dir, exist_ok=True)
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    logfile = os.path.join(log_dir, f"abstract_finder_console_{timestamp}.log")
    latest_symlink = os.path.join(log_dir, "abstract_finder_console.log")

    # Rotate latest symlink
    try:
        if os.path.islink(latest_symlink) or os.path.exists(latest_symlink):
            os.remove(latest_symlink)
        os.symlink(logfile, latest_symlink)
    except Exception:
        pass

    sys.stdout = open(logfile, "w", buffering=1)
    sys.stderr = sys.stdout
    print(f"[{timestamp}] Finder Console launched. Logs → {logfile}")
    return logfile


def main():
    logfile = setup_logger()
    try:
        # ── Determine target directory ────────────────────────────────
def main():
    try:
        # ── Determine target directory ────────────────────────────────
        target_dir = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
        if not os.path.isdir(target_dir):
            target_dir = os.path.dirname(target_dir)
        os.chdir(target_dir)  # real working directory for the console
        startFinderConsole()

    except Exception as e:
        traceback.print_exc()
        print(f"❌ Finder Console crashed: {e}")
        print(f"See log file for details → {logfile}")
        raise


if __name__ == "__main__":
    main()
