import logging

from flask import Blueprint, flash, redirect, render_template, session, url_for

from app import db
from app.auth import ensure_fresh_token, get_active_account, login_required
from app.models import Account, ScheduledPost
from app.services.errors import ServiceError
from app.tiktok_api import TikTokAPIError, get_user_info, list_videos

account_bp = Blueprint("account", __name__)
log = logging.getLogger(__name__)


@account_bp.route("/dashboard")
@login_required
def dashboard():
    account = get_active_account()
    recent_videos = []
    pending_count = 0

    try:
        token = ensure_fresh_token(account)
        user = get_user_info(token)
        if user:
            for field in ("display_name", "avatar_url", "follower_count", "following_count", "likes_count", "video_count"):
                if user.get(field) is not None:
                    setattr(account, field, user[field] if field in ("display_name", "avatar_url") else int(user[field]))
            db.session.commit()
        recent_videos = list_videos(token, max_count=5)["videos"]
    except (TikTokAPIError, ServiceError) as e:
        flash(e.message, "warning")
    except Exception:
        log.error("dashboard.refresh failed", exc_info=True)
        flash("Could not refresh account data.", "warning")

    pending_count = ScheduledPost.query.filter_by(account_id=account.id, status=ScheduledPost.STATUS_PENDING).count()
    all_accounts = Account.query.order_by(Account.display_name).all()
    return render_template(
        "dashboard.html",
        account=account,
        accounts=all_accounts,
        recent_videos=recent_videos,
        pending_count=pending_count,
    )


@account_bp.route("/accounts")
@login_required
def accounts():
    all_accounts = Account.query.order_by(Account.display_name).all()
    active_id = session.get("active_account_id")
    return render_template("accounts.html", accounts=all_accounts, active_id=active_id)


@account_bp.route("/accounts/add")
@login_required
def add_account():
    return redirect(url_for("auth.auth_start"))


@account_bp.route("/accounts/<int:account_db_id>/activate", methods=["POST"])
@login_required
def activate_account(account_db_id):
    account = Account.query.get_or_404(account_db_id)
    session["active_account_id"] = account.id
    flash(f"Switched to account: {account.display_name}", "success")
    return redirect(url_for("account.dashboard"))


@account_bp.route("/accounts/<int:account_db_id>/refresh", methods=["POST"])
@login_required
def refresh_account(account_db_id):
    account = Account.query.get_or_404(account_db_id)
    try:
        token = ensure_fresh_token(account)
        user = get_user_info(token)
        if user:
            account.display_name = user.get("display_name") or account.display_name
            account.avatar_url = user.get("avatar_url") or account.avatar_url
            for field in ("follower_count", "following_count", "likes_count", "video_count"):
                if user.get(field) is not None:
                    setattr(account, field, int(user[field]))
            db.session.commit()
        flash("Account data refreshed.", "success")
    except (TikTokAPIError, ServiceError) as e:
        flash(e.message, "error")
    except Exception:
        log.error("accounts.refresh failed", exc_info=True)
        flash("Could not refresh the account.", "error")
    return redirect(url_for("account.accounts"))


@account_bp.route("/accounts/<int:account_db_id>/delete", methods=["POST"])
@login_required
def delete_account(account_db_id):
    account = Account.query.get_or_404(account_db_id)
    name = account.display_name
    db.session.delete(account)
    db.session.commit()
    if session.get("active_account_id") == account_db_id:
        session.pop("active_account_id", None)
    flash(f"Disconnected account: {name}", "info")
    remaining = Account.query.order_by(Account.display_name).first()
    if remaining:
        session["active_account_id"] = remaining.id
    return redirect(url_for("account.dashboard"))
