from __future__ import annotations

from typing import Any

from flow_xhs.runtime.database.manager import DatabaseManager


class FileAccountRepository:
    @staticmethod
    def _resolve_account(platform: str, account_uid: str) -> dict[str, Any] | None:
        target = str(account_uid or "").strip()
        if not target:
            return None
        accounts = DatabaseManager.get_all_accounts(only_active=False)
        for item in accounts:
            if item.get("platform") != platform:
                continue
            if str(item.get("user_no") or "").strip() == target:
                return item
        return None

    @staticmethod
    def _to_cli_account(item: dict[str, Any]) -> dict[str, Any]:
        output = dict(item)
        output.pop("storage_state", None)
        output["account_uid"] = output.get("user_no")
        return output

    def list_accounts(self, platform: str = "Rednote", only_active: bool = True) -> list[dict[str, Any]]:
        accounts = DatabaseManager.get_all_accounts(only_active=only_active)
        filtered = [acc for acc in accounts if acc.get("platform") == platform]
        return [self._to_cli_account(item) for item in filtered]

    def delete(self, platform: str, account_uid: str) -> bool:
        record = self._resolve_account(platform=platform, account_uid=account_uid)
        if not record:
            return False
        DatabaseManager.delete_account(platform, record["user_no"])
        return True

    def activate(self, platform: str, account_uid: str) -> bool:
        record = self._resolve_account(platform=platform, account_uid=account_uid)
        if not record:
            return False
        return DatabaseManager.set_account_login_status(platform=platform, user_no=record["user_no"], is_logged_in=True)

    def deactivate(self, platform: str, account_uid: str) -> bool:
        record = self._resolve_account(platform=platform, account_uid=account_uid)
        if not record:
            return False
        return DatabaseManager.set_account_login_status(platform=platform, user_no=record["user_no"], is_logged_in=False)
