"""
Dockrion Generated Runtime
==========================
Agent: {{ agent.name }}
{%- if agent.handler %}
Mode: Handler (direct callable)
Handler: {{ agent.handler }}
{%- else %}
Mode: Entrypoint (framework agent)
Framework: {{ agent.framework }}
Entrypoint: {{ agent.entrypoint }}
{%- endif %}
Description: {{ agent.description | default('Dockrion Agent', true) }}

Auto-generated by Dockrion SDK v{{ dockrion_version | default('1.0.0') }}
Do not edit manually - regenerate using `dockrion build`
"""
import sys
import os
from pathlib import Path

# Add project root to Python path for agent module imports
# Use dockrion_common utility for consistent path resolution
from dockrion_common import setup_module_path

current_dir = Path(__file__).parent
{% if agent.handler -%}
module_path = "{{ agent.handler }}"
{% else -%}
module_path = "{{ agent.entrypoint }}"
{% endif -%}

# Setup Python path to find the agent module
project_root = setup_module_path(module_path, current_dir.parent)

from dockrion_runtime import create_app
from dockrion_schema import DockSpec

# Try to load .env from project root (if python-dotenv is available)
try:
    from dotenv import load_dotenv
    env_file = project_root / '.env'
    load_dotenv(env_file)
except ImportError:
    pass  # python-dotenv not installed, skip .env loading

# ============================================================================
# Agent Specification (Embedded from Dockfile.yaml)
# ============================================================================

SPEC_DATA = {{ spec_python }}

# ============================================================================
# Create Application
# ============================================================================

# Parse and validate the embedded specification
spec = DockSpec.model_validate(SPEC_DATA)

# Create the FastAPI application using the runtime factory
{%- if agent.handler %}
# Handler mode: direct callable function
app = create_app(
    spec=spec,
    agent_handler="{{ agent.handler }}"
)
{%- else %}
# Entrypoint mode: framework agent
app = create_app(
    spec=spec,
    agent_entrypoint="{{ agent.entrypoint }}"
)
{%- endif %}

# ============================================================================
# Main Entry Point
# ============================================================================

if __name__ == "__main__":
    import uvicorn
    
    host = "{{ expose.host | default('0.0.0.0') if expose else '0.0.0.0' }}"
    port = {{ expose.port | default(8080) if expose else 8080 }}
    
    print(f"🚀 Starting {{ agent.name }} on {host}:{port}")
    uvicorn.run(
        app,
        host=host,
        port=port,
        log_level="info"
    )

