from archo.schemas.architecture import ArchitectureResponse


def generate_mermaid(data: ArchitectureResponse) -> str:
    """Convert architecture JSON into a high-level Mermaid diagram string."""
    name = data.service_name
    language = data.language
    framework = data.framework
    databases = data.databases or []
    outbound = data.outbound_calls or []

    lines = ["graph LR"]
    framework_and_language = f"{framework} / {language}" if framework != "none" else language
    lines.append(f'    {name}["{name}<br>({framework_and_language})"]')
    lines.append("")

    for db in databases:
        node_id = db.type.replace(" ", "_")
        label = f"{db.type}<br>({', '.join(db.collections_or_tables)})" if db.collections_or_tables else db.type
        lines.append(f'    {node_id}[("{label}")]')

    for call in outbound:
        node_id = call.target_service.replace(" ", "_").replace("-", "_")
        lines.append(f'    {node_id}["{call.target_service}"]')

    lines.append("")
    # lines.append(f"    client --> {name}")

    for db in databases:
        node_id = db.type.replace(" ", "_")
        lines.append(f"    {name} --> {node_id}")

    for call in outbound:
        node_id = call.target_service.replace(" ", "_").replace("-", "_")
        lines.append(f"    {name} --> {node_id}")

    return "\n".join(lines) + "\n"


def write_mermaid(data: ArchitectureResponse, output_path: str = "ARCHITECTURE.mermaid") -> None:
    """Write the Mermaid diagram to a file."""
    print(f"Generating {output_path}...")
    content = generate_mermaid(data)
    try:
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"Done — {output_path} written.")
    except Exception as e:
        raise RuntimeError(f"Failed to write {output_path}: {e}")
