from __future__ import annotations
import asyncio
import queue
import threading
import uuid
from dataclasses import dataclass
from typing import Any
from flownet.compiler.flow_def import BoundFlow
from flownet.api.actor_method_ref import ActorMethodRef


        

    

class Actor:
    def __init__(self, actor_id: str, object: Any, config: Any | None = None):
        self.object = object
        self.lock = threading.Lock()
        self.actor_id = actor_id
        self.config = config

        # 可选：状态统计，自定义调度策略等
    
    def __getattr__(self, name):
        attr = getattr(self.object, name, None)
        no_lock = getattr(attr, "__flownet_no_lock__", False)

        if isinstance(attr, ActorMethodRef):
            return attr

        if isinstance(attr, BoundFlow):
            def compile_task(*args, **kwargs):
                if no_lock:
                    return attr.compile(*args, **kwargs)
                with self.lock:
                    return attr.compile(*args, **kwargs)
            return compile_task

        elif callable(attr):
            if asyncio.iscoroutinefunction(attr):
                async def async_call(*args, **kwargs):
                    if no_lock:
                        return await attr(*args, **kwargs)
                    await asyncio.to_thread(self.lock.acquire)
                    try:
                        return await attr(*args, **kwargs)
                    finally:
                        self.lock.release()
                return async_call
            else:
                def sync_call(*args, **kwargs):
                    if no_lock:
                        return attr(*args, **kwargs)
                    with self.lock:
                        return attr(*args, **kwargs)
                return sync_call

        else:
            return attr
