import logging
import os

# Write logs to app.log in the deployment root (one level above this file)
_log_path = os.path.join(os.path.dirname(__file__), '..', 'app.log')
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)s: %(message)s',
    handlers=[
        logging.FileHandler(_log_path),
        logging.StreamHandler(),
    ],
)
logger = logging.getLogger(__name__)

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .routers import auth, shifts, staff, customers, pumps, dashboard
from .routers import roster, leave, allowances, performance, settings, cash, analytics, shift_collections, collection_cycles, tank_readings
from .routers import stock, reports, audit
from .routers import users, billing, bulk_sales, notifications, expenses, monitoring
from .routers import role_permissions as role_perms_router
from .routers import database_manager as db_mgr_router
from .routers import shift_templates as shift_templates_router
from .routers import pump_configs as pump_configs_router
from .routers import dip_charts as dip_charts_router

app = FastAPI(
    title="Fuel Station Management API",
    version="1.0.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",
        "http://localhost:3000",
        "http://127.0.0.1:5173",
        "https://fuelops.docura.lk",
        "http://fuelops.docura.lk",
        "https://dunhindabrothers.com",
        "http://dunhindabrothers.com",
        "https://www.dunhindabrothers.com",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auth.router,      prefix="/api/auth",      tags=["Auth"])
app.include_router(shifts.router,    prefix="/api/shifts",    tags=["Shifts"])
app.include_router(staff.router,     prefix="/api/staff",     tags=["Staff"])
app.include_router(customers.router, prefix="/api/customers", tags=["Customers"])
app.include_router(pumps.router,     prefix="/api",           tags=["Pumps & Rates"])
app.include_router(dashboard.router,    prefix="/api/dashboard",  tags=["Dashboard"])
app.include_router(roster.router,       prefix="/api",             tags=["Roster"])
app.include_router(leave.router,        prefix="/api",             tags=["Leave"])
app.include_router(allowances.router,   prefix="/api",             tags=["Allowances"])
app.include_router(performance.router,  prefix="/api",             tags=["Performance"])
app.include_router(settings.router,     prefix="/api",             tags=["Settings"])
app.include_router(cash.router,         prefix="/api",             tags=["Cash Handovers"])
app.include_router(analytics.router,         prefix="/api", tags=["Analytics"])
app.include_router(shift_collections.router,  prefix="/api", tags=["Shift Collections"])
app.include_router(collection_cycles.router, prefix="/api", tags=["Collection Cycles"])
app.include_router(tank_readings.router,    prefix="/api/tank-readings", tags=["Tank Dip"])
app.include_router(stock.router,          prefix="/api",         tags=["Stock"])
app.include_router(reports.router,        prefix="/api",         tags=["Reports"])
app.include_router(audit.router,          prefix="/api",         tags=["Audit"])
app.include_router(users.router,          prefix="/api",         tags=["Users"])
app.include_router(billing.router,        prefix="/api",         tags=["Billing"])
app.include_router(bulk_sales.router,     prefix="/api",         tags=["Bulk Sales"])
app.include_router(notifications.router,  prefix="/api",         tags=["Notifications"])
app.include_router(expenses.router,       prefix="/api",         tags=["Expenses"])
app.include_router(monitoring.router,        prefix="/api",         tags=["Monitoring"])
app.include_router(role_perms_router.router, prefix="/api",         tags=["Role Permissions"])
app.include_router(db_mgr_router.router,        prefix="/api",         tags=["Database Manager"])
app.include_router(shift_templates_router.router, prefix="/api",       tags=["Shift Templates"])
app.include_router(pump_configs_router.router,    prefix="/api",       tags=["Pump Configs"])
app.include_router(dip_charts_router.router,      prefix="/api",       tags=["Dip Charts"])

SKIP_LOG_PATHS = {
    '/api/monitoring/health', '/api/monitoring/transactions',
    '/api/monitoring/stats',  '/api/monitoring/response-times',
    '/api/monitoring/error-rates', '/api/monitoring/endpoint-stats',
}

@app.middleware("http")
async def log_requests(request: Request, call_next):
    import time
    from .database import SessionLocal
    from .models import TransactionLog
    from .auth import decode_token

    start = time.monotonic()
    logger.info(f"{request.method} {request.url.path}")
    try:
        response = await call_next(request)
        if response.status_code >= 400:
            logger.warning(f"{request.method} {request.url.path} -> {response.status_code}")
    except Exception as exc:
        logger.error(f"{request.method} {request.url.path} -> UNHANDLED: {exc}", exc_info=True)
        return JSONResponse(status_code=500, content={"detail": "Internal server error"})

    duration_ms = int((time.monotonic() - start) * 1000)
    method = request.method
    path = str(request.url.path)
    if method not in ('HEAD', 'OPTIONS') and response.status_code < 500 and path not in SKIP_LOG_PATHS:
        user_id = None
        try:
            auth_header = request.headers.get('authorization', '')
            if auth_header.startswith('Bearer '):
                payload = decode_token(auth_header[7:])
                user_id = int(payload.get('sub'))
        except Exception:
            pass
        ip = request.client.host if request.client else None
        try:
            db = SessionLocal()
            db.add(TransactionLog(
                user_id=user_id,
                endpoint=str(request.url.path),
                method=method,
                status_code=response.status_code,
                duration_ms=duration_ms,
                ip_address=ip,
            ))
            db.commit()
            db.close()
        except Exception:
            pass

    return response



@app.on_event("startup")
def run_migrations():
    from .database import engine
    with engine.connect() as conn:
        try:
            conn.execute(__import__('sqlalchemy').text(
                "ALTER TABLE expenses ADD COLUMN IF NOT EXISTS staff_id INT NULL"
            ))
            conn.execute(__import__('sqlalchemy').text(
                "ALTER TABLE expenses ADD CONSTRAINT IF NOT EXISTS fk_expenses_staff "
                "FOREIGN KEY (staff_id) REFERENCES staff(id) ON DELETE SET NULL"
            ))
            conn.commit()
            logger.info("Migration: expenses.staff_id ensured")
        except Exception as e:
            logger.warning(f"Migration skipped (may already exist): {e}")


@app.get("/api/health", tags=["Health"])
def health():
    return {"status": "ok", "version": "1.0.0"}
