import sys

from nova_cli.cli.shell import NovaShell
from nova_cli.nova_core.ai.api_client import BridgeyeAPIClient
from nova_cli import config as cli_config
from nova_cli.nova_core.auth.storage import is_logged_in, has_refresh_token


def _doctor() -> int:
    api = BridgeyeAPIClient()

    print("NOVA CLI — Doctor")
    print(f"- NOVA_API_BASE_URL:  {cli_config.NOVA_API_BASE_URL}")
    print(f"- NOVA_AUTH_BASE_URL: {cli_config.NOVA_AUTH_BASE_URL}")
    print(f"- Default provider:   {cli_config.DEFAULT_PROVIDER}")
    print(f"- Default model:      {cli_config.DEFAULT_MODEL}")

    api_ok = api.health()
    print(f"- API reachable:      {'yes' if api_ok else 'no'}")

    logged_in = is_logged_in()
    print(f"- Logged in:          {'yes' if logged_in else 'no'}")

    # Helpful extra signal: refresh token presence
    rt = has_refresh_token()
    print(f"- Has refresh token:  {'yes' if rt else 'no'}")

    if not api_ok:
        print("\nFix:")
        print("  1) Start NOVA_API")
        print("  2) Or set NOVA_API_BASE_URL to the right host/port")
        return 1

    if not logged_in:
        print("\nFix:")
        print("  Run: nova login")
        return 1

    return 0


def main():
    shell = NovaShell()

    # No args => interactive
    if len(sys.argv) == 1:
        shell.run()
        return

    cmd = sys.argv[1]
    args = " ".join(sys.argv[2:]) if len(sys.argv) > 2 else ""

    if cmd in ("help", "--help", "-h"):
        shell.cmd_help("")
        return

    if cmd == "doctor":
        raise SystemExit(_doctor())

    if cmd == "run":
        shell.cmd_run(args)
        return

    if cmd == "clean":
        shell.cmd_clean(args)
        return

    if cmd == "login":
        shell.cmd_login(args)
        return

    # Optional legacy alias
    if cmd == "heal":
        shell.cmd_run(args)
        return

    # Anything else => treat as chat prompt (one-shot)
    prompt = " ".join(sys.argv[1:])
    shell.handle_ai_request(prompt)


if __name__ == "__main__":
    main()
