import typer
from pathlib import Path
from .server import run

app = typer.Typer(help="Cardinal CLI — FastAPI USSD Framework")

@app.command()
def new(name: str):
    project_dir = Path(name)
    project_dir.mkdir(parents=True, exist_ok=True)
    (project_dir / "__init__.py").touch()

    template = f"""from cardinal import ussd_app, ussd

@ussd_app.route('start')
def start():
    ussd.screen('main_menu')
    return f"Welcome {ussd.msisdn}!\n1. Check Balance\n2. Transfer Funds"

@ussd_app.route('main_menu')
def main_menu():
    return "Choose an option:\n1. Balance\n2. Transfer"

@ussd_app.routes['main_menu'].option('1')
def show_balance():
    ussd.screen('balance')
    return f"{ussd.msisdn}, your balance is $100."

@ussd_app.routes['main_menu'].option('2')
def to_transfer():
    ussd.screen('transfer')
    return "Enter amount to transfer:"

@ussd_app.route('transfer')
def transfer():
    ussd.screen('end')
    return f"Transferred ${{ussd.input}} successfully for {ussd.msisdn}."

@ussd_app.route('balance')
def balance():
    ussd.screen('end')
    return f"Your balance is $100, {ussd.msisdn}."

@ussd_app.route('end')
def end():
    return f"Thank you for using Cardinal, {ussd.msisdn}."
"""
    with open(project_dir / "main.py", "w") as f:
        f.write(template.strip())
    typer.echo(f"✅ Project '{name}' created successfully!")

@app.command()
def runserver(app_path: str = "main.py", host: str = "0.0.0.0", port: int = 8000):
    run(app_path, host=host, port=port)

if __name__ == "__main__":
    app()
