# Copyright (c) 2020 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#
import webbrowser

from rich.console import Console
from tabulate import tabulate

# Initialize Rich console
console = Console()

from src.api.v4_organizations import get_organizations


def open_webpage(arguments):
    query = (arguments["<ID-or-NAME>"] or "02fa7d30-c3de-4e0a-8f1e-2de120e7fd23").lower()
    enabled_only = not arguments.get("--all")

    # Get organizations using the consolidated v4 API
    # Convert enabled_only to filter parameters
    org_data = get_organizations(organization_query=query if query != "02fa7d30-c3de-4e0a-8f1e-2de120e7fd23" else None)

    # Filter organizations if needed (enabled_only logic)
    if enabled_only:
        org_data = {
            org_id: org for org_id, org in org_data.items() if getattr(org, "organization_enabled", getattr(org, "organizations_enabled", False))
        }

    # Convert Pydantic models to dict format for compatibility
    org_data = {org_id: org.model_dump() for org_id, org in org_data.items()}

    if len(org_data) == 1:
        for org_id, details in org_data.items():
            if arguments["--link-only"]:
                print(f"{details['cz_organization_name'].capitalize()} - https://app.cloudzero.com?organization_id={org_id}")
            else:
                print(f"Loading {details['cz_organization_name']} ({org_id})")
                webbrowser.open(f"https://app.cloudzero.com?organization_id={org_id}", new=2)
            break  # just to be sure
    elif len(org_data) > 1:
        org_data_list = [
            {
                "Name": v["cz_organization_name"].capitalize(),
                "Site": v.get("website"),
                "Enabled": v.get("organization_enabled", False),
                "Stage": v.get("organization_stage", ""),
                "CZ Organization ID": k,
                "Link": f"https://app.cloudzero.com?organization_id={k}",
            }
            for k, v in org_data.items()
        ]
        console.print(
            f"\nFound multiple organizations with a name similar to '{query}', please refine your search\n",
            style="bold white",
        )
        print(tabulate(org_data_list, headers="keys", tablefmt="rounded_outline"))

    else:
        print(f"No organizations matching {query} found, please refine your search")
