"""Fix code-server bind address to include port

Revision ID: 2026_05_29_fix_code_server_bind_addr_port
Revises: 2026_05_29_remove_lsio_command_override
Create Date: 2026-05-29 18:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import yaml

# revision identifiers, used by Alembic.
revision: str = "2026_05_29_fix_code_server_bind_addr_port"
down_revision: Union[str, None] = "2026_05_29_remove_lsio_command_override"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _fix_tool_type_templates(conn) -> None:
    """Fix code-server tool type templates with broken --host override."""
    result = conn.execute(
        sa.text("""
            SELECT id, compose_template, default_port
            FROM tool_types
            WHERE name = 'code-server'
            AND compose_template LIKE '%--host%'
        """)
    ).fetchall()

    for tool_id, compose_template, default_port in result:
        port = default_port or 8443
        expected = f"--bind-addr 0.0.0.0:{port}"

        # Replace any line containing --host with the correct bind-addr
        lines = compose_template.split("\n")
        new_lines = []
        modified = False
        for line in lines:
            if "command:" in line and "--host" in line:
                indent = line[: len(line) - len(line.lstrip())]
                new_lines.append(f"{indent}command: {expected}")
                modified = True
            else:
                new_lines.append(line)

        if not modified:
            continue

        updated = "\n".join(new_lines)
        conn.execute(
            sa.text("""
                UPDATE tool_types
                SET compose_template = :compose_template
                WHERE id = :id
            """),
            {"compose_template": updated, "id": tool_id},
        )
        print(f"Fixed code-server template ({tool_id}): replaced --host with {expected}")


def _fix_instance_compose_files(conn) -> None:
    """Fix existing instance compose files on disk with broken --host override."""
    from pathlib import Path

    # Use information_schema to check if compose_path column exists
    col_result = conn.execute(
        sa.text("""
            SELECT column_name
            FROM information_schema.columns
            WHERE table_name = 'tool_instances'
            AND column_name = 'compose_path'
        """)
    ).fetchone()

    if not col_result:
        print("compose_path column not found, skipping instance file fixes")
        return

    result = conn.execute(
        sa.text("""
            SELECT id, compose_path, tool_type_id
            FROM tool_instances
            WHERE compose_path IS NOT NULL
        """)
    ).fetchall()

    for instance_id, compose_path, tool_type_id in result:
        path = Path(compose_path)
        if not path.exists():
            continue

        try:
            content = path.read_text()
        except Exception:
            continue

        if "--host" not in content:
            continue

        # Get default_port from tool_type
        port_result = conn.execute(
            sa.text("""
                SELECT default_port FROM tool_types WHERE id = :id
            """),
            {"id": tool_type_id},
        ).fetchone()
        port = port_result[0] if port_result and port_result[0] else 8443
        expected = f"--bind-addr 0.0.0.0:{port}"

        try:
            data = yaml.safe_load(content)
        except Exception:
            continue

        if not data or "services" not in data:
            continue

        modified = False
        for svc in data["services"].values():
            if "command" in svc:
                cmd = svc["command"]
                if "--host" in cmd:
                    svc["command"] = expected
                    modified = True

        if not modified:
            continue

        try:
            path.write_text(yaml.dump(data, default_flow_style=False))
            print(
                f"Fixed code-server instance compose ({instance_id}): "
                f"replaced --host with {expected}"
            )
        except Exception as exc:
            print(f"Failed to fix instance {instance_id}: {exc}")


def upgrade() -> None:
    conn = op.get_bind()
    _fix_tool_type_templates(conn)
    _fix_instance_compose_files(conn)


def downgrade() -> None:
    pass
