"""Export zone data to TOML files."""

from __future__ import annotations

from pathlib import Path

from mudlib.portal import Portal
from mudlib.zone import Zone


def export_zone(zone: Zone) -> str:
    """Export a Zone to TOML string.

    Args:
        zone: Zone instance to export

    Returns:
        TOML-formatted string representation of the zone
    """
    lines = []

    # Basic fields
    lines.append(f'name = "{zone.name}"')
    if zone.description:
        lines.append(f'description = "{zone.description}"')
    lines.append(f"width = {zone.width}")
    lines.append(f"height = {zone.height}")
    lines.append(f"toroidal = {str(zone.toroidal).lower()}")
    lines.append(f"spawn_x = {zone.spawn_x}")
    lines.append(f"spawn_y = {zone.spawn_y}")
    if zone.safe:
        lines.append("safe = true")
    lines.append("")

    # Terrain section
    lines.append("[terrain]")
    lines.append("rows = [")
    for row in zone.terrain:
        row_str = "".join(row)
        lines.append(f'    "{row_str}",')
    lines.append("]")
    lines.append("")

    # Impassable tiles
    lines.append("[terrain.impassable]")
    impassable_list = sorted(zone.impassable)
    tiles_str = ", ".join(f'"{tile}"' for tile in impassable_list)
    lines.append(f"tiles = [{tiles_str}]")

    # Ambient messages (if present)
    if zone.ambient_messages:
        lines.append("")
        lines.append("[ambient]")
        lines.append(f"interval = {zone.ambient_interval}")
        lines.append("messages = [")
        for msg in zone.ambient_messages:
            # Escape quotes in messages
            escaped_msg = msg.replace('"', '\\"')
            lines.append(f'    "{escaped_msg}",')
        lines.append("]")

    # Portals (if any)
    portals = [obj for obj in zone._contents if isinstance(obj, Portal)]
    if portals:
        lines.append("")
        for portal in portals:
            lines.append("[[portals]]")
            lines.append(f"x = {portal.x}")
            lines.append(f"y = {portal.y}")
            target = f"{portal.target_zone}:{portal.target_x},{portal.target_y}"
            lines.append(f'target = "{target}"')
            lines.append(f'label = "{portal.name}"')
            if portal.aliases:
                aliases_str = ", ".join(f'"{alias}"' for alias in portal.aliases)
                lines.append(f"aliases = [{aliases_str}]")
            lines.append("")

    # Spawn rules (if any)
    if zone.spawn_rules:
        for spawn_rule in zone.spawn_rules:
            lines.append("[[spawns]]")
            lines.append(f'mob = "{spawn_rule.mob}"')
            lines.append(f"max_count = {spawn_rule.max_count}")
            lines.append(f"respawn_seconds = {spawn_rule.respawn_seconds}")
            if spawn_rule.home_region is not None:
                hr = spawn_rule.home_region
                lines.append(
                    f"home_region = {{ x = [{hr['x'][0]}, {hr['x'][1]}], "
                    f"y = [{hr['y'][0]}, {hr['y'][1]}] }}"
                )
            lines.append("")

    # Boundaries (if any)
    if zone.boundaries:
        for boundary in zone.boundaries:
            lines.append("[[boundaries]]")
            lines.append(f'name = "{boundary.name}"')
            lines.append(f"x = [{boundary.x_min}, {boundary.x_max}]")
            lines.append(f"y = [{boundary.y_min}, {boundary.y_max}]")
            if boundary.on_enter_message is not None:
                escaped = boundary.on_enter_message.replace('"', '\\"')
                lines.append(f'on_enter_message = "{escaped}"')
            if boundary.on_exit_message is not None:
                escaped = boundary.on_exit_message.replace('"', '\\"')
                lines.append(f'on_exit_message = "{escaped}"')
            if boundary.on_exit_check is not None:
                lines.append(f'on_exit_check = "{boundary.on_exit_check}"')
            if boundary.on_exit_fail is not None:
                escaped = boundary.on_exit_fail.replace('"', '\\"')
                lines.append(f'on_exit_fail = "{escaped}"')
            lines.append("")

    return "\n".join(lines)


def export_zone_to_file(zone: Zone, path: Path) -> None:
    """Export a Zone to a TOML file.

    Args:
        zone: Zone instance to export
        path: Path where the TOML file should be written
    """
    toml_str = export_zone(zone)
    path.write_text(toml_str)
