import os
from pathlib import Path

import typer
import yaml
from rich.console import Console

console = Console()


def init_app(name: str) -> None:
    """
    Initialize a new application within the current project root.
    
    Args:
        name: The name of the application to create (e.g., 'inventory', 'pricing').
    """

    # 1. Validation: Ensure we are in a Sibi Flux project root (check for pyproject.toml as heuristic)
    cwd = Path(os.getcwd())
    if not (cwd / "pyproject.toml").exists():
        console.print("[yellow]Warning: pyproject.toml not found. Are you in a project root?[/yellow]")

    app_dir = cwd / name

    if app_dir.exists():
        console.print(f"[red]Error: Application directory '{name}' already exists.[/red]")
        raise typer.Exit(code=1)

    console.print(f"[bold blue]Initializing new application: {name}[/bold blue]")

    # 2. Create Directory Structure
    structure = [
        "api",
        "datacubes",
        "readers",
        "aggregators",
    ]

    app_dir.mkdir()
    (app_dir / "__init__.py").touch()

    for folder in structure:
        path = app_dir / folder
        path.mkdir()
        (path / "__init__.py").touch()

    # 2.1 Create datacubes extension registry template
    datacubes_yaml = app_dir / "datacubes" / "datacubes.yaml"
    template_yaml = """
cubes: []
# Define your app-specific datacube extensions here
# - source: dataobjects.gencubes.ibis_dev.products.products_cubes.ProductsDc
#   name: LogisticsProductsDc
#   module: products  # -> logistics/datacubes/products.py
"""
    datacubes_yaml.write_text(template_yaml.strip())

    # 3. Create Basic Router Template
    router_template = f"""
from fastapi import APIRouter

router = APIRouter()

@router.get("/")
async def root():
    return {{"message": "Hello from {name}!"}}
"""
    (app_dir / "api" / "main.py").write_text(router_template.strip())

    # 4. Register in conf/apps.yaml
    conf_dir = cwd / "conf"
    if not conf_dir.exists():
        conf_dir.mkdir()

    apps_yaml_path = conf_dir / "apps.yaml"

    apps_data = {"apps": []}
    if apps_yaml_path.exists():
        try:
            with open(apps_yaml_path, "r") as f:
                loaded = yaml.safe_load(f)
                if loaded and isinstance(loaded, dict) and "apps" in loaded:
                    apps_data = loaded
                elif loaded is None:
                    pass  # empty file
                else:
                    console.print(
                        f"[yellow]Warning: conf/apps.yaml has unexpected structure. Initializing with empty list.[/yellow]")
        except Exception as e:
            console.print(f"[yellow]Warning: Could not read existing apps.yaml: {e}[/yellow]")

    if name not in apps_data["apps"]:
        apps_data["apps"].append(name)
        with open(apps_yaml_path, "w") as f:
            yaml.dump(apps_data, f, default_flow_style=False)
        console.print(f"[green]Registered '{name}' in conf/apps.yaml[/green]")
    else:
        console.print(f"[yellow]App '{name}' already registered in conf/apps.yaml[/yellow]")

    # 5. Success Message & Instructions
    console.print(f"[bold green]Successfully created application '{name}'![/bold green]")
    console.print(f"Location: {name}/")
    console.print("\n[yellow]Next Step:[/yellow]")
    console.print(f"1. Run [bold]sibi-flux env[/bold] to automatically register your new router in [bold]main.py[/bold].")
