"""CLI entry point — extracts --profile BEFORE any Flowly module import.

This is critical because many modules evaluate ``get_flowly_home()`` at
import time (module-level constants).  By setting ``FLOWLY_HOME`` here,
before ``from flowly.cli.commands import app`` runs, every constant
resolves to the correct profile directory.

Resolution order:
  1. ``-p`` / ``--profile`` CLI flag  (highest priority)
  2. ``FLOWLY_PROFILE`` env var       (for wrapper scripts)
  3. ``~/.flowly/active_profile``     (sticky default)
  4. ``"default"``                    (fallback)
"""

from __future__ import annotations

import os
import sys


def main() -> None:
    """Parse profile flag, set FLOWLY_HOME, then launch the typer app."""
    profile: str | None = None
    argv = sys.argv[1:]

    # 1. Extract -p / --profile from argv (before typer sees it)
    for i, arg in enumerate(argv):
        if arg in ("-p", "--profile") and i + 1 < len(argv):
            profile = argv[i + 1]
            sys.argv = [sys.argv[0]] + argv[:i] + argv[i + 2:]
            break
        if arg.startswith("--profile="):
            profile = arg.split("=", 1)[1]
            sys.argv = [sys.argv[0]] + argv[:i] + argv[i + 1:]
            break

    # 2. Check FLOWLY_PROFILE env var (wrapper scripts set this)
    if profile is None:
        profile = os.environ.get("FLOWLY_PROFILE")

    # 3. Check ~/.flowly/active_profile (sticky default)
    if profile is None:
        from flowly.profile import get_active_profile
        active = get_active_profile()
        if active != "default":
            profile = active

    # 4. Set FLOWLY_HOME before ANY other flowly import
    from flowly.profile import set_profile
    set_profile(profile)

    # NOW it's safe to import the rest of flowly
    from flowly.cli.commands import app
    app()


if __name__ == "__main__":
    main()
