"""
TaxForge CLI - Launch the tax preparation app
"""
import subprocess
import sys
import os
from pathlib import Path


__version__ = "0.9.0"


def main():
    """Main entry point for taxforge command."""
    args = sys.argv[1:]
    
    if args and args[0] in ("--version", "-v"):
        print(f"TaxForge v{__version__}")
        return 0
    
    if args and args[0] in ("--help", "-h"):
        print(f"""TaxForge v{__version__} - AI-powered tax preparation

Usage:
  taxforge [run]     Launch the web UI (default)
  taxforge --version Show version
  taxforge --help    Show this help

After running, open http://localhost:3000 in your browser.
Go to Settings to configure your Gemini API key first.
""")
        return 0
    
    # Find the ui directory
    # When installed via pip, it's in the package
    ui_dir = Path(__file__).parent.parent
    rxconfig = ui_dir / "rxconfig.py"
    
    if not rxconfig.exists():
        # Try relative to current dir
        if Path("rxconfig.py").exists():
            ui_dir = Path(".")
        elif Path("ui/rxconfig.py").exists():
            ui_dir = Path("ui")
        else:
            print("Error: Cannot find rxconfig.py")
            print("Please run from the TaxForge directory or install via pip")
            return 1
    
    print(f"🔨 Starting TaxForge v{__version__}...")
    print(f"   Directory: {ui_dir.absolute()}")
    print(f"   Open http://localhost:3000 after startup")
    print()
    
    os.chdir(ui_dir)
    
    # Run reflex
    try:
        result = subprocess.run(
            [sys.executable, "-m", "reflex", "run"],
            cwd=ui_dir,
        )
        return result.returncode
    except KeyboardInterrupt:
        print("\n👋 TaxForge stopped")
        return 0
    except FileNotFoundError:
        print("Error: Reflex not installed. Run: pip install reflex")
        return 1


if __name__ == "__main__":
    sys.exit(main())
