import asyncio
import os
import traceback
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import select
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
from starlette.datastructures import URL

# Absolute path for testing
BASE_DIR = r"C:/Users/MF Sangadji/bestweb"
DATABASE_URL = f"sqlite+aiosqlite:///{os.path.join(BASE_DIR, 'billing.db')}"

async def diagnose():
    print("--- START DIAGNOSTIC ---")
    try:
        # 1. Test Database
        from app.models.models import Customer
        engine = create_async_engine(DATABASE_URL)
        session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
        
        async with session_factory() as session:
            print("Testing Database Query...")
            result = await session.execute(select(Customer).limit(1))
            customer = result.scalar_one_or_none()
            print(f"Query Success. Customer found: {customer.name if customer else 'None'}")

        # 2. Test Template Rendering
        print("Testing Template Rendering...")
        templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))
        
        # Mock request
        scope = {
            "type": "http",
            "scheme": "http",
            "server": ("127.0.0.1", 8000),
            "path": "/customers",
            "headers": [],
        }
        mock_request = Request(scope)
        
        # Try render
        response = templates.TemplateResponse(
            request=mock_request,
            name="customers.html",
            context={"customers": []}
        )
        print("Template Rendering Success.")
        
    except Exception:
        print("!!! ERROR DETECTED !!!")
        traceback.print_exc()
    print("--- END DIAGNOSTIC ---")

if __name__ == "__main__":
    asyncio.run(diagnose())
