"""Encrypted credential storage (PyCypherLib / PyCypher)."""
from __future__ import annotations

import os

from PyCypher import Cy


class CredentialManager:
    """Store and load Telegram token + chat dict encrypted with a password (PyCypherLib)."""

    def __init__(self, filename: str = "tgrdata.cy") -> None:
        self.filename = filename

    def signup(self, token: str, chat_dict: dict[str, str], password: str) -> None:
        """Create encrypted file with token and chat IDs. Fails if file already exists."""

        if os.path.exists(self.filename):
            raise FileExistsError("Encrypted file already exists.")
        lines = [token] + [f"{name}:{cid}" for name, cid in chat_dict.items()]
        Cy().encLines(self.filename).Lines(lines).P(password)

    def login(self, password: str) -> tuple[str, dict[str, str]]:
        """Read encrypted file and return (token, chat_dict)."""
        if not os.path.exists(self.filename):
            raise FileNotFoundError("Encrypted file not found.")
        try:
            lines = Cy().decLines(self.filename).P(password)
        except Exception as e:
            raise ValueError("Invalid password or corrupted encrypted file.") from e
        token = lines[0]
        chat_dict: dict[str, str] = {}
        for element in lines[1:]:
            name, cid = element.split(":", 1)
            chat_dict[name] = cid
        return token, chat_dict


__all__ = ["CredentialManager"]
