from __future__ import annotations

import os
from pathlib import Path

from ..serve.asgi import build_app
from .loader import load_agent_class
from .local import ensure_local_workspace, load_env_file


def create_app():
    project = Path(os.environ.get("A2A_PROJECT_DIR", ".")).resolve()
    entrypoint = os.environ["A2A_ENTRYPOINT"]
    env_file = Path(os.environ.get("A2A_ENV_FILE", project / ".env.local"))
    load_env_file(env_file)
    workspace = ensure_local_workspace(
        project,
        workspace=Path(os.environ["A2A_LOCAL_WORKSPACE_DIR"])
        if os.environ.get("A2A_LOCAL_WORKSPACE_DIR")
        else None,
    )
    os.environ.setdefault("A2A_LOCAL_DEV", "1")
    os.environ.setdefault("A2A_LOCAL_WORKSPACE_DIR", str(workspace))
    cls = load_agent_class(entrypoint, project_dir=project)
    return build_app(cls())
