from datetime import datetime, timezone, timedelta
import secrets
from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, or_, asc, desc
from app.core.database import get_db
from app.core.security import require_roles
from app.models.models import Voucher, VoucherAgent, VoucherBatch, HotspotProfile, MikrotikDevice, Site
import os
from app.core.secrets import decrypt_secret

router = APIRouter(dependencies=[Depends(require_roles("agen_voucher", "admin_cs"))])
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))

@router.get("/vouchers", response_class=HTMLResponse)
async def vouchers_page(request: Request, db: AsyncSession = Depends(get_db)):
    now = datetime.now(timezone.utc)
    active_expiring = (await db.execute(select(Voucher).where(
        Voucher.expires_at != None,
        Voucher.expires_at < now,
        Voucher.status.in_(["available", "sold"])
    ))).scalars().all()
    for voucher in active_expiring:
        voucher.status = "expired"
    if active_expiring:
        await db.commit()

    agents = (await db.execute(
        select(VoucherAgent).where(VoucherAgent.is_active == True).order_by(VoucherAgent.name)
    )).scalars().all()
    profiles = (await db.execute(
        select(HotspotProfile).where(HotspotProfile.is_active == True).order_by(HotspotProfile.name)
    )).scalars().all()
    devices = (await db.execute(
        select(MikrotikDevice).where(MikrotikDevice.is_active == True).order_by(MikrotikDevice.name)
    )).scalars().all()
    sites = (await db.execute(
        select(Site).where(Site.is_active == True).order_by(Site.name)
    )).scalars().all()
    batches = (await db.execute(
        select(VoucherBatch).order_by(VoucherBatch.created_at.desc())
    )).scalars().all()
    total_count = (await db.scalar(select(func.count(Voucher.id)))) or 0
    profile_usage = {}
    voucher_counts = (await db.execute(
        select(Voucher.profile_id, func.count(Voucher.id)).group_by(Voucher.profile_id)
    )).all()
    batch_counts = (await db.execute(
        select(VoucherBatch.profile_id, func.count(VoucherBatch.id)).group_by(VoucherBatch.profile_id)
    )).all()
    for profile_id, count in voucher_counts:
        if profile_id is not None:
            profile_usage.setdefault(profile_id, {"vouchers": 0, "batches": 0})["vouchers"] = count
    for profile_id, count in batch_counts:
        if profile_id is not None:
            profile_usage.setdefault(profile_id, {"vouchers": 0, "batches": 0})["batches"] = count

    return templates.TemplateResponse(request=request, name="vouchers.html", context={
        "vouchers": [],
        "agents": agents,
        "profiles": profiles,
        "devices": devices,
        "sites": sites,
        "batches": batches,
        "profile_usage": profile_usage,
        "protected_profiles": set(),
        "can_delete_profile": False,
        "total_count": total_count,
        "total_vouchers": total_count,
    })


@router.get("/api/vouchers/datatable")
async def vouchers_datatable(request: Request, db: AsyncSession = Depends(get_db)):
    params = request.query_params
    try:
        draw = max(0, int(params.get("draw", 0)))
        start = max(0, int(params.get("start", 0)))
        length = int(params.get("length", 10))
        profile_id = int(params.get("profile_id")) if params.get("profile_id") else None
    except (TypeError, ValueError):
        draw, start, length, profile_id = 0, 0, 10, None
    length = 100 if length < 1 else min(length, 100)

    base = select(Voucher)
    filters = []
    if profile_id is not None:
        filters.append(Voucher.profile_id == profile_id)
    batch = (params.get("batch") or "").strip()
    if batch:
        filters.append(or_(
            Voucher.comment == batch,
            Voucher.batch_id.in_(select(VoucherBatch.id).where(VoucherBatch.batch_code == batch)),
        ))

    total = await db.scalar(select(func.count(Voucher.id))) or 0
    filtered_query = base.where(*filters) if filters else base
    search = (params.get("search[value]") or "").strip()
    if search:
        pattern = f"%{search}%"
        filtered_query = filtered_query.where(or_(
            Voucher.code.ilike(pattern),
            Voucher.username.ilike(pattern),
            Voucher.profile.ilike(pattern),
            Voucher.status.ilike(pattern),
            Voucher.comment.ilike(pattern),
        ))
    filtered = await db.scalar(select(func.count()).select_from(filtered_query.subquery())) or 0

    order_columns = {
        0: Voucher.id,
        1: Voucher.username,
        3: Voucher.profile,
        4: Voucher.price,
        5: Voucher.status,
        6: Voucher.comment,
    }
    try:
        order_index = int(params.get("order[0][column]", 0))
    except ValueError:
        order_index = 0
    order_column = order_columns.get(order_index, Voucher.id)
    ordering = desc(order_column) if params.get("order[0][dir]", "desc").lower() == "desc" else asc(order_column)

    vouchers = (await db.execute(
        filtered_query.order_by(ordering, Voucher.id.desc()).offset(start).limit(length)
    )).scalars().all()
    rows = []
    for voucher in vouchers:
        username = voucher.username or voucher.code
        password = username
        if voucher.credential_mode == "separate" and voucher.password_ciphertext:
            password = decrypt_secret(voucher.password_ciphertext)
        rows.append({
            "id": voucher.id,
            "username": username,
            "password": password,
            "credential_mode": voucher.credential_mode or "legacy_same",
            "profile": voucher.profile,
            "price": voucher.price or 0,
            "status": voucher.status,
            "comment": voucher.comment or "",
        })
    return JSONResponse({"draw": draw, "recordsTotal": total, "recordsFiltered": filtered, "data": rows}, headers={"Cache-Control": "no-store, private", "Pragma": "no-cache", "X-Content-Type-Options": "nosniff"})

@router.post("/vouchers/generate")
async def generate_vouchers(profile: str = Form(...), price: int = Form(...), quantity: int = Form(...), duration_days: int = Form(30), db: AsyncSession = Depends(get_db)):
    quantity = max(1, min(quantity, 500))
    duration_days = max(1, min(duration_days, 365))
    expires_at = datetime.now(timezone.utc) + timedelta(days=duration_days)
    for _ in range(quantity):
        code = secrets.token_urlsafe(6).upper().replace("-", "")
        db.add(Voucher(code=code, profile=profile.strip(), price=price, status="available", expires_at=expires_at))
    await db.commit()
    return RedirectResponse(url="/vouchers", status_code=303)

@router.post("/vouchers/{voucher_id}/sell")
async def sell_voucher(voucher_id: int, agent_id: int = Form(...), db: AsyncSession = Depends(get_db)):
    voucher = await db.get(Voucher, voucher_id)
    agent = await db.get(VoucherAgent, agent_id)
    if voucher and agent and agent.is_active and voucher.status == "available" and (not voucher.expires_at or voucher.expires_at > datetime.now(timezone.utc)):
        voucher.agent_id = agent.id
        voucher.status = "sold"
        voucher.sold_at = datetime.now(timezone.utc)
        await db.commit()
    return RedirectResponse(url="/vouchers", status_code=303)

@router.post("/vouchers/{voucher_id}/use")
async def use_voucher(voucher_id: int, db: AsyncSession = Depends(get_db)):
    voucher = await db.get(Voucher, voucher_id)
    if voucher and voucher.status == "sold" and (not voucher.expires_at or voucher.expires_at > datetime.now(timezone.utc)):
        voucher.status = "used"
        voucher.used_at = datetime.now(timezone.utc)
        await db.commit()
    return RedirectResponse(url="/vouchers", status_code=303)
