from archo.schemas.architecture import ArchitectureResponse


def generate_markdown(data: ArchitectureResponse) -> str:
    """Convert architecture JSON into a readable ARCHO.md string."""
    lines = []

    lines.append(f"# {data.service_name}")
    lines.append("")
    lines.append(f"**Language:** {data.language}  ")
    if data.framework != "none":
        lines.append(f"**Framework:** {data.framework}  ")
    lines.append("")

    if data.routes:
        lines.append("## Routes")
        lines.append("")
        for r in data.routes:
            lines.append(f"- `{r.method}` {r.path}")
        lines.append("")

    outbound = data.outbound_calls or []
    if outbound:
        lines.append("## Outbound Calls")
        lines.append("")
        for call in outbound:
            lines.append(f"- **{call.target_service}** via {call.via}")
        lines.append("")

    if data.pubsub:
        subscribes = data.pubsub.subscribes
        publishes = data.pubsub.publishes
        if subscribes or publishes:
            lines.append("## Pub/Sub")
            lines.append("")
            if subscribes:
                lines.append("**Subscribes:**")
                for topic in subscribes:
                    lines.append(f"- {topic}")
            if publishes:
                lines.append("**Publishes:**")
                for topic in publishes:
                    lines.append(f"- {topic}")
            lines.append("")

    databases = data.databases or []
    if databases:
        lines.append("## Databases")
        lines.append("")
        for db in databases:
            if db.collections_or_tables:
                lines.append(f"**{db.type}:** {', '.join(db.collections_or_tables)}")
            else:
                lines.append(f"**{db.type}**")
        lines.append("")

    return "\n".join(lines)
