#!/usr/bin/env python3
"""BRICK_pl - Plotting CLI for BRICK Knowledge Graph visualization."""

import argparse
import sys
import pandas as pd
import networkx as nx


def main():
    parser = argparse.ArgumentParser(
        description="BRICK_pl - Visualization tools for BRICK Knowledge Graph",
        usage='BRICK_pl <command> [options]'
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available plot types")
    
    # interact - interactive network
    interact_parser = subparsers.add_parser("interact", help="Interactive network visualization (HTML)")
    interact_parser.add_argument("-i", "--input", required=True, help="Input graph file (graphml, gml, etc.)")
    interact_parser.add_argument("-o", "--output", default="network.html", help="Output HTML file (default: network.html)")
    interact_parser.add_argument("--width", type=int, default=800, help="Width in pixels (default: 800)")
    interact_parser.add_argument("--height", type=int, default=600, help="Height in pixels (default: 600)")
    
    # static - static network
    static_parser = subparsers.add_parser("static", help="Static network visualization (PNG/PDF)")
    static_parser.add_argument("-i", "--input", required=True, help="Input graph file")
    static_parser.add_argument("-o", "--output", default="network.png", help="Output image file (default: network.png)")
    static_parser.add_argument("--root", help="Root node for hierarchical layout")
    
    # radial - radial enrichment plot
    radial_parser = subparsers.add_parser("radial", help="Radial enrichment plot")
    radial_parser.add_argument("-i", "--input", required=True, help="Input CSV file with query results")
    radial_parser.add_argument("-o", "--output", default="radial.png", help="Output image file (default: radial.png)")
    radial_parser.add_argument("--top-k", type=int, default=7, help="Top K entities to show (default: 7)")
    
    # tf - TF regulon visualization
    tf_parser = subparsers.add_parser("tf", help="TF-Regulon network visualization")
    tf_parser.add_argument("-i", "--input", required=True, help="Input CSV file with TF regulon data")
    tf_parser.add_argument("--tf", required=True, help="Transcription factor name(s), comma-separated")
    tf_parser.add_argument("--verified", help="Verified genes file (one gene per line)")
    tf_parser.add_argument("-o", "--output", default="tf_regulon.png", help="Output image file")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    try:
        if args.command == "interact":
            cmd_interact(args)
        elif args.command == "static":
            cmd_static(args)
        elif args.command == "radial":
            cmd_radial(args)
        elif args.command == "tf":
            cmd_tf(args)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_interact(args):
    """Interactive network visualization."""
    from .interact_graph import interact_visualize_network
    
    # Load graph
    if args.input.endswith('.graphml'):
        nxg = nx.read_graphml(args.input)
    elif args.input.endswith('.gml'):
        nxg = nx.read_gml(args.input)
    else:
        raise ValueError(f"Unsupported file format: {args.input}")
    
    print(f"Loaded graph with {nxg.number_of_nodes()} nodes and {nxg.number_of_edges()} edges")
    
    interact_visualize_network(
        nxg, 
        width=args.width, 
        height=args.height, 
        notebook=False, 
        save=args.output
    )
    print(f"Saved interactive visualization to {args.output}")


def cmd_static(args):
    """Static network visualization."""
    from .static_graph import static_visualize_network
    
    # Load graph
    if args.input.endswith('.graphml'):
        nxg = nx.read_graphml(args.input)
    elif args.input.endswith('.gml'):
        nxg = nx.read_gml(args.input)
    else:
        raise ValueError(f"Unsupported file format: {args.input}")
    
    print(f"Loaded graph with {nxg.number_of_nodes()} nodes and {nxg.number_of_edges()} edges")
    
    static_visualize_network(nxg, root=args.root, save_path=args.output)
    print(f"Saved static visualization to {args.output}")


def cmd_radial(args):
    """Radial enrichment plot."""
    from .radial_enrich import radial_enrich_plot
    
    # Load data
    df = pd.read_csv(args.input)
    
    print(f"Loaded {len(df)} records")
    
    fig = radial_enrich_plot(df, top_k=args.top_k)
    fig.savefig(args.output, dpi=300, bbox_inches='tight')
    print(f"Saved radial plot to {args.output}")


def cmd_tf(args):
    """TF-Regulon visualization."""
    from .visulize_tf_regulon import visualize_tf_regulon
    
    # Load data
    df = pd.read_csv(args.input)
    df.set_index(df.columns[0], inplace=True)
    
    tf_list = [t.strip() for t in args.tf.split(",")]
    
    verified_genes = []
    if args.verified:
        with open(args.verified, 'r') as f:
            verified_genes = [line.strip() for line in f if line.strip()]
    
    print(f"Visualizing TF: {tf_list}")
    
    visualize_tf_regulon(tf_list, df, verified_genes, save_path=args.output)


if __name__ == "__main__":
    main()
