"""
ZSyncTech Studio SDK - Execution Monitoring Framework.
"""
import logging
import sys
from datetime import datetime
from rich.console import Console
from rich.logging import RichHandler
from rich.text import Text


class StudioLogHandler(RichHandler):
    """Custom log handler with timestamp and level formatting."""

    def render_message(self, record, message):
        """Render message content."""
        return message

    def render(self, record, traceback, message_renderable):
        """Render log line with timestamp, level, and message."""
        timestamp = datetime.fromtimestamp(record.created)
        time_str = timestamp.strftime('%H:%M:%S.') + f'{int(timestamp.microsecond / 1000):03d}'

        level_colors = {
            'DEBUG': 'blue',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red bold'
        }
        level_color = level_colors.get(record.levelname, 'white')

        output = Text()
        output.append(time_str, style='dim cyan')
        output.append(' | ', style='dim')
        output.append(f'{record.levelname:<8}', style=level_color)
        output.append(' | ', style='dim')
        output.append(message_renderable)

        return output


console = Console(file=sys.stderr, force_terminal=True, width=120)

logging.basicConfig(
    level=logging.INFO,
    format='%(message)s',
    handlers=[
        StudioLogHandler(
            console=console,
            rich_tracebacks=True,
            show_time=False,
            show_level=False,
            show_path=False,
            markup=True,
            omit_repeated_times=False
        )
    ]
)

# Disable keyword highlighting
for handler in logging.root.handlers:
    if isinstance(handler, RichHandler):
        handler.KEYWORDS = []

from .core import (
    execution,
    task,
    step,
    get_current_execution,
    get_current_task,
    set_total_tasks,
    ExecutionFunction,
)

from .models import (
    Execution,
    Task,
    Step,
    ExecutionRun,
    TaskRun,
    StepRun,
    ExecutionStatus,
    TaskStatus,
    StepStatus,
)

from .observers import (
    Observer,
    ConsoleObserver,
    CallbackObserver,
    register_observer,
    on_event,
    disable_default_observer,
    set_default_observer,
)

from .platform import (
    PlatformObserver,
)

from .server import (
    serve,
    ExecutionServer,
)

from .config import (
    get_environment_config,
    set_deployment_config,
    EnvironmentConfig,
    Credential,
    InputOutputTypes,
)

from importlib.metadata import version

__version__ = version("zsynctech-studio-sdk")

_default_observer = ConsoleObserver(verbose=True)
register_observer(_default_observer)
set_default_observer(_default_observer)

__all__ = [
    # Decorators
    "execution",
    "task",
    "step",
    # Types
    "ExecutionFunction",
    # Context
    "get_current_execution",
    "get_current_task",
    "set_total_tasks",
    # Models
    "Execution",
    "Task",
    "Step",
    "ExecutionRun",
    "TaskRun",
    "StepRun",
    "ExecutionStatus",
    "TaskStatus",
    "StepStatus",
    # Observers
    "Observer",
    "ConsoleObserver",
    "CallbackObserver",
    "register_observer",
    "on_event",
    "disable_default_observer",
    # Platform
    "PlatformObserver",
    "ExecutionStatus",
    "TaskStatus",
    "StepStatus",
    # Server
    "serve",
    "ExecutionServer",
    # Config
    "get_environment_config",
    "set_deployment_config",
    "EnvironmentConfig",
    "Credential",
    "InputOutputTypes",
]
