"""Bridge configuration: a persisted pairing token and the listen port."""

from __future__ import annotations

import json
import os
import secrets
from dataclasses import dataclass
from pathlib import Path

DEFAULT_PORT = 8765


@dataclass(frozen=True)
class BridgeConfig:
    pairing_token: str
    port: int
    # L10: opt-in local transcript of tool substance (files/commands/diffs).
    # Privacy-first — must read as OFF until the user turns it on, same
    # convention as backend/services/user_settings.py's
    # SECURITY_DEFAULTS['telemetry']. This is a host-local toggle, not a
    # backend user-setting: the whole point is that it stays on the user's
    # own machine.
    transcripts_enabled: bool = False

    @classmethod
    def load(cls, home_dir: Path | None = None, port: int = DEFAULT_PORT) -> "BridgeConfig":
        home = home_dir or Path.home()
        path = home / ".atashi" / "bridge.json"
        if path.exists():
            data = json.loads(path.read_text())
            return cls(
                pairing_token=data["pairing_token"],
                port=int(data.get("port", port)),
                transcripts_enabled=bool(data.get("transcripts_enabled", False)),
            )

        token = secrets.token_urlsafe(32)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.parent.chmod(0o700)
        # The pairing token authenticates a client to the tool-executing bridge:
        # write it owner-only from creation (O_CREAT with 0o600 so there is no
        # world-readable window), then chmod to defeat a permissive umask.
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as fh:
            fh.write(json.dumps({"pairing_token": token, "port": port, "transcripts_enabled": False}))
        path.chmod(0o600)
        return cls(pairing_token=token, port=port, transcripts_enabled=False)

    @classmethod
    def set_transcripts_enabled(cls, enabled: bool, home_dir: Path | None = None) -> "BridgeConfig":
        """Flip the local opt-in without minting a new pairing token."""
        cfg = cls.load(home_dir=home_dir)
        home = home_dir or Path.home()
        path = home / ".atashi" / "bridge.json"
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as fh:
            fh.write(json.dumps({
                "pairing_token": cfg.pairing_token,
                "port": cfg.port,
                "transcripts_enabled": enabled,
            }))
        path.chmod(0o600)
        return cls(pairing_token=cfg.pairing_token, port=cfg.port, transcripts_enabled=enabled)
