"""
AutoPIL server entry point.

Used by the `autopil-serve` console script installed by pip.
Can also be invoked directly: python -m autopil.cli
"""

import argparse
import os
from pathlib import Path


DEFAULT_POLICY = str(Path(__file__).parent.parent / "policies" / "financial_services.yaml")
DEFAULT_DB     = "autopil_audit.db"


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="autopil-serve",
        description="AutoPIL API Server — context governance for autonomous agents",
    )
    parser.add_argument("--policy", default=os.environ.get("AUTOPIL_POLICY", DEFAULT_POLICY),
                        help="Path to policy YAML file")
    parser.add_argument("--db",     default=os.environ.get("AUTOPIL_DB", DEFAULT_DB),
                        help="Path to SQLite audit DB (ignored if DATABASE_URL is set)")
    parser.add_argument("--host",   default=os.environ.get("AUTOPIL_HOST", "0.0.0.0"),
                        help="Host to bind")
    parser.add_argument("--port",   default=int(os.environ.get("AUTOPIL_PORT", "8000")), type=int,
                        help="Port to listen on")
    args = parser.parse_args()

    try:
        import uvicorn
        from autopil.api import create_app
        from autopil.db import create_stores
    except ImportError as e:
        raise SystemExit(
            f"\nMissing server dependencies: {e}\n"
            "Install with: pip install autopil[server]\n"
        ) from e

    database_url = os.environ.get("DATABASE_URL")

    print(f"\n  AutoPIL API Server")
    print(f"  Policy   : {args.policy}")
    if database_url:
        safe_url = database_url.split("@")[-1] if "@" in database_url else database_url
        print(f"  Database : postgres @ {safe_url}")
    else:
        print(f"  Database : sqlite @ {args.db}")

    # ── bootstrap tenant + superadmin key on first start ─────────────────────
    _, key_store, tenant_store, _ = create_stores(database_url=database_url, db_path=args.db)
    if tenant_store.count() == 0:
        tenant_id = tenant_store.create_tenant("default")
        _, plaintext = key_store.create_key("superadmin", tenant_id=tenant_id, is_superadmin=True)
        print(f"\n  ⚠  First start — created 'default' tenant and superadmin key:")
        print(f"     {plaintext}")
        print(f"     Save this — it will not be shown again.\n")
    elif key_store.count() == 0:
        tenants = tenant_store.list_tenants()
        tenant_id = tenants[0]["tenant_id"]
        _, plaintext = key_store.create_key("superadmin", tenant_id=tenant_id, is_superadmin=True)
        print(f"\n  ⚠  No API keys found. Generated superadmin key for tenant '{tenants[0]['name']}':")
        print(f"     {plaintext}")
        print(f"     Save this — it will not be shown again.\n")

    print(f"  Docs     : http://localhost:{args.port}/docs\n")

    app = create_app(
        policy_path=args.policy,
        audit_db=args.db,
        database_url=database_url,
    )
    uvicorn.run(app, host=args.host, port=args.port, reload=False)


if __name__ == "__main__":
    main()
