# implementation of swaysome in python
import sys
from dataclasses import dataclass
from swayipc import Swayipc, Output, Workspace
import pathlib

class SwaySome(Swayipc):
    def __init__(self):
        super().__init__()

    def _cmd(self, cmd_str):
        self.cmd(cmd_str)

    def ordered_outputs(self):
        outs = self.outputs()
        outs.sort(key=lambda o: o.name)
        return outs

    def current_workspace(self):
        outs = self.outputs()
        wss = self.workspaces()

        focused_output = next((o.name for o in outs if o.focused), None)
        if not focused_output:
            raise RuntimeError("No focused output")

        for ws in wss:
            if ws.visible and ws.output == focused_output:
                return ws.num

        raise RuntimeError("No active workspace found")

    def group_base(self):
        return (self.current_workspace() // 10) * 10

    def resolve(self, n: int):
        return self.group_base() + n

    def focus(self, n: int):
        self._cmd(f"workspace number {self.resolve(n)}")

    def move(self, n: int):
        self._cmd(f"move container to workspace number {self.resolve(n)}")

    def focus_abs(self, n: int):
        self._cmd(f"workspace number {n}")

    def move_abs(self, n: int):
        self._cmd(f"move container to workspace number {n}")

    def init(self, n: int):
        outputs = self.ordered_outputs()
        current = next((o.name for o in outputs if o.focused), None)

        for i, out in enumerate(outputs):
            target = ((i + 1) * 10) + n
            self._cmd(f"focus output {out.name}")
            self._cmd(f"workspace number {target}")

        if current:
            self._cmd(f"focus output {current}")

def main():
    cmd = sys.argv[1]
    n = int(sys.argv[2])

    sway = SwaySome()

    if cmd == "focus":
        sway.focus(n)
    elif cmd == "move":
        sway.move(n)
    elif cmd == "focus-abs":
        sway.focus_abs(n)
    elif cmd == "move-abs":
        sway.move_abs(n)
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()