#!/usr/bin/env python3
import sys, os, json
from PyQt6.QtCore import QCoreApplication
from PyQt6.QtNetwork import QLocalServer, QLocalSocket
import json, os, sys
from .src import startFinderConsole

APP_KEY = "abstract_finder_console"

def send_to_existing_instance(target_dir: str) -> bool:
    """Try sending target_dir to an already running console."""
    sock = QLocalSocket()
    sock.connectToServer(APP_KEY)
    if not sock.waitForConnected(200):
        return False  # no instance
    payload = json.dumps({"dir": target_dir}).encode()
    sock.write(payload)
    sock.flush()
    sock.waitForBytesWritten(200)
    sock.close()
    return True

def run_new_instance(target_dir: str):
    """Run the full console, register for future messages."""
    from PyQt6.QtWidgets import QApplication
    app = QApplication.instance() or QApplication(sys.argv)
    server = QLocalServer()
    if not server.listen(APP_KEY):
        # Remove stale socket and retry
        QLocalServer.removeServer(APP_KEY)
        server.listen(APP_KEY)

    win = startFinderConsole()

    # handler for incoming "change dir" requests
    def on_new_connection():
        client = server.nextPendingConnection()
        if not client:
            return
        if client.waitForReadyRead(1000):
            data = bytes(client.readAll()).decode()
            try:
                msg = json.loads(data)
                new_dir = msg.get("dir")
                if new_dir and os.path.isdir(new_dir):
                    # find and update the dir_in field
                    if hasattr(win, "dir_in"):
                        win.dir_in.setText(new_dir)
                    # bring window to front
                    win.showNormal()
                    win.raise_()
                    win.activateWindow()
            except Exception as e:
                print("Message error:", e)
        client.disconnectFromServer()

    server.newConnection.connect(on_new_connection)
    app.exec()

if __name__ == "__main__":
    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)

    # if an instance is already running, just send it the new dir
    if send_to_existing_instance(target_dir):
        sys.exit(0)

    # otherwise start a fresh console
    run_new_instance(target_dir)
