import logging,os
from typing import Set
from localstack import config
from localstack.aws.accounts import get_aws_account_id
from localstack.services.stores import AccountRegionBundle
from localstack.state.inspect import ReflectionStateLocator,ServiceBackendCollectorVisitor
from localstack.utils.aws.aws_stack import get_valid_regions_for_service
from localstack.utils.files import load_file
from localstack.utils.strings import to_bytes
from moto.core import BackendDict
from localstack_ext.bootstrap.pods.service_state.service_state_types import AccountRegion
LOG=logging.getLogger(__name__)
class ServiceStateManager:
	def __init__(A,service):A.service=service
	def active_service_regions(B):
		A=B._active_service_regions()
		if B.service=='stepfunctions':
			C=os.path.join(config.dirs.data,B.service,'backend_state')
			if os.path.exists(C):
				try:D=load_file(C,mode='rb');A=[A for A in A if to_bytes(A.region)in D]
				except Exception:pass
			return set(A)
		return A
	def _active_service_regions(D):
		def B(reg):return AccountRegion(account_id=get_aws_account_id(),region=reg)
		def G(account_id):
			A=account_id
			if A=='123456789012':return get_aws_account_id()
			return A
		E=ServiceBackendCollectorVisitor();H=ReflectionStateLocator(service=D.service);H.accept_state_visitor(visitor=E);F=E.collect()
		if not F:I=get_valid_regions_for_service(D.service);return set([B(A)for A in I])
		C=set()
		for (M,A) in F.items():
			if isinstance(A,(BackendDict,AccountRegionBundle)):
				for (J,K) in A.items():
					for L in K.keys():C.add(AccountRegion(account_id=G(J),region=L))
			elif isinstance(A,dict):C.update(set([B(A)for A in A.keys()]))
			else:return{B('global')}
		return C