import typer
from pathlib import Path

# Package-relative imports
from .core import connect_file, list_files
from .loader import parse_file
from .injector import extract_function
from .deployer import serve  # This provides the `coral8 serve` command

app = typer.Typer(help="🚧 coral8: zero-config file loader & simple HTTP bridge")

@app.command()
def connect(path: str, alias: str = None):
    """Register a file at `path` so coral8 can load it later."""
    success = connect_file(path, alias)
    if success:
        typer.secho(f"✅ Connected: {path}", fg=typer.colors.GREEN)
    else:
        typer.secho(f"❌ Failed to connect: {path}", fg=typer.colors.RED)

@app.command("import")
def import_file(alias: str):
    """Load the registered file by alias and show a summary."""
    files = list_files()
    if alias not in files:
        typer.secho(f"Alias '{alias}' not found.", fg=typer.colors.RED)
        raise typer.Exit(code=1)
    path = files[alias]["path"]
    data = parse_file(path)
    if isinstance(data, list):
        typer.secho(f"Loaded {len(data)} items from '{alias}'.", fg=typer.colors.GREEN)
    else:
        typer.secho(f"Loaded data of type {type(data).__name__} from '{alias}'.", fg=typer.colors.GREEN)

@app.command("list")
def list_files_cmd():
    """Show all files you’ve registered with coral8."""
    files = list_files()
    if not files:
        typer.echo("No files registered. Use `coral8 connect <path>` first.")
        raise typer.Exit()
    for name, info in files.items():
        typer.echo(f"{name}  —  {info['path']}  ({info['type']})")

@app.command()
def inject(source: str, symbol: str, target: str):
    """Inject a function or class from one .py to another."""
    code = extract_function(Path(source), symbol)
    with open(target, "a", encoding="utf-8") as f:
        f.write(f"\n\n# bridged from {source}\n{code}\n")
    typer.secho(f"✅ Injected `{symbol}` from {source} to {target}", fg=typer.colors.GREEN)

# Commented out until deploy_file is implemented
# @app.command()
# def deploy(alias: str):
#     """Deploy the registered file by alias over HTTP or other protocol."""
#     files = list_files()
#     if alias not in files:
#         typer.secho(f"Alias '{alias}' not found.", fg=typer.colors.RED)
#         raise typer.Exit(code=1)
#     path = files[alias]["path"]
#     deploy_file(path)
#     typer.secho(f"✅ Deployed: {alias}", fg=typer.colors.GREEN)

if __name__ == "__main__":
    app()



