# app/pipeline/routes.py
# This module implements the pipeline management features

from datetime import datetime
from decimal import Decimal
from flask import Blueprint, render_template, request, redirect, url_for, flash, abort
from flask_login import login_required, current_user

from .. import db
from ..utils import require_perm
from sqlalchemy import func
from ..models import (
    PipelineStage, Opportunity, OpportunityStageHistory,
    Lead, EmployeeProfile, ClientBranch
)

pipeline_bp = Blueprint("pipeline", __name__, template_folder="../templates")


def _opp_code_next():
    last = Opportunity.query.order_by(Opportunity.id.desc()).first()
    nxt = (last.id + 1) if last else 1
    return f"OP-{nxt:06d}"


def _get_stage_by_name(name: str):
    return PipelineStage.query.filter(func.lower(PipelineStage.name) == name.strip().lower()).first()


def _lead_has_opportunity(lead_id: int) -> bool:
    if not lead_id:
        return False
    return Opportunity.query.filter_by(lead_id=lead_id).first() is not None

def _to_decimal(v, default="0"):
    try:
        s = str(v or "").strip().replace(",", "")
        if not s:
            return Decimal(default)
        return Decimal(s)
    except Exception:
        return Decimal(default)


def _team_user_ids(manager_user_id: int, include_self: bool = True):
    seen = set([manager_user_id]) if include_self else set()
    stack = [manager_user_id]

    while stack:
        mid = stack.pop()
        rows = (
            EmployeeProfile.query
            .filter(EmployeeProfile.reporting_manager_user_id == mid)
            .with_entities(EmployeeProfile.user_id)
            .all()
        )
        for (uid,) in rows:
            if uid is not None and uid not in seen:
                seen.add(uid)
                stack.append(uid)

    return list(seen)


def _allowed_owner_ids():
    if current_user.has_perm("pipeline.view_all"):
        return None
    return _team_user_ids(current_user.id, include_self=True)


def _require_opp_access(o: Opportunity):
    allowed = _allowed_owner_ids()
    if allowed is None:
        return
    if o.owner_id not in set(allowed):
        abort(403)


@pipeline_bp.route("/")
@login_required
@require_perm("pipeline.view")
def board():
    stages = (
        PipelineStage.query
        .filter_by(is_active=True)
        .order_by(PipelineStage.sort_order.asc())
        .all()
    )

    today = datetime.utcnow().date()
    closed_stage_names = {"Won", "Closed Won", "Lost", "Closed Lost"}

    search = (request.args.get("search") or "").strip()
    stage_id = request.args.get("stage_id", type=int)
    owner_id = request.args.get("owner_id", type=int)
    quote_status = (request.args.get("quote_status") or "").strip()
    overdue = (request.args.get("overdue") or "").strip()
    close_month = request.args.get("close_month", type=int)
    close_year = request.args.get("close_year", type=int)

    qs = Opportunity.query.order_by(Opportunity.updated_at.desc())

    allowed = _allowed_owner_ids()
    if allowed is not None:
        qs = qs.filter(Opportunity.owner_id.in_(allowed))

    if owner_id:
        if allowed is None or owner_id in allowed:
            qs = qs.filter(Opportunity.owner_id == owner_id)

    if stage_id:
        qs = qs.filter(Opportunity.stage_id == stage_id)

    if search:
        like = f"%{search}%"
        qs = qs.filter(
            db.or_(
                Opportunity.title.ilike(like),
                Opportunity.company.ilike(like),
                Opportunity.opp_code.ilike(like),
                Opportunity.contact_name.ilike(like),
                Opportunity.contact_email.ilike(like),
            )
        )

    if close_month and close_year:
        start_date = datetime(close_year, close_month, 1).date()
        if close_month == 12:
            end_date = datetime(close_year + 1, 1, 1).date()
        else:
            end_date = datetime(close_year, close_month + 1, 1).date()

        qs = qs.filter(
            Opportunity.expected_close_date >= start_date,
            Opportunity.expected_close_date < end_date
        )

    opps = qs.all()

    filtered_opps = []
    for o in opps:
        stage_name = o.stage.name if o.stage else ""
        is_closed = stage_name in closed_stage_names
        is_overdue = o.expected_close_date and o.expected_close_date < today and not is_closed
        has_quote = o.quotes.count() > 0

        if overdue == "1" and not is_overdue:
            continue

        if quote_status == "with_quote" and not has_quote:
            continue

        if quote_status == "without_quote" and has_quote:
            continue

        filtered_opps.append(o)

    grouped = {s.id: [] for s in stages}
    for o in filtered_opps:
        if o.stage_id in grouped:
            grouped[o.stage_id].append(o)

    visible_owner_ids = allowed
    if visible_owner_ids is None:
        owners = (
            EmployeeProfile.query
            .join(EmployeeProfile.user)
            .filter(EmployeeProfile.user.has(is_active=True))
            .all()
        )
    else:
        owners = (
            EmployeeProfile.query
            .join(EmployeeProfile.user)
            .filter(EmployeeProfile.user_id.in_(visible_owner_ids))
            .filter(EmployeeProfile.user.has(is_active=True))
            .all()
        )

    total_value = sum((_to_decimal(o.expected_value) for o in filtered_opps), Decimal("0"))
    overdue_count = 0
    with_quote_count = 0

    for o in filtered_opps:
        stage_name = o.stage.name if o.stage else ""
        is_closed = stage_name in closed_stage_names
        if o.expected_close_date and o.expected_close_date < today and not is_closed:
            overdue_count += 1
        if o.quotes.count() > 0:
            with_quote_count += 1

    months = [
        (1, "January"), (2, "February"), (3, "March"), (4, "April"),
        (5, "May"), (6, "June"), (7, "July"), (8, "August"),
        (9, "September"), (10, "October"), (11, "November"), (12, "December")
    ]

    years = list(range(today.year - 3, today.year + 3))

    summary = {
        "total_opportunities": len(filtered_opps),
        "total_value": total_value,
        "overdue_count": overdue_count,
        "with_quote_count": with_quote_count,
        "without_quote_count": len(filtered_opps) - with_quote_count,
    }

    return render_template(
        "pipeline/board.html",
        stages=stages,
        grouped=grouped,
        today=today,
        closed_stage_names=closed_stage_names,
        owners=owners,
        months=months,
        years=years,
        summary=summary,
        filters={
            "search": search,
            "stage_id": stage_id,
            "owner_id": owner_id,
            "quote_status": quote_status,
            "overdue": overdue,
            "close_month": close_month,
            "close_year": close_year,
        }
    )

@pipeline_bp.route("/new", methods=["GET", "POST"])
@login_required
@require_perm("pipeline.create")
def create():
    stages = (
        PipelineStage.query
        .filter_by(is_active=True)
        .order_by(PipelineStage.sort_order.asc())
        .all()
    )

    lead_id_qs = request.args.get("lead_id")
    lead_from_qs = Lead.query.get(int(lead_id_qs)) if (lead_id_qs and lead_id_qs.isdigit()) else None

    # Only show leads that are NOT already converted
    leads_query = Lead.query
    if not current_user.has_perm("leads.view_all"):
        allowed_ids = _allowed_owner_ids()
        if allowed_ids is not None:
            leads_query = leads_query.filter(Lead.owner_id.in_(allowed_ids))

    leads = (
        leads_query
        .outerjoin(Opportunity, Opportunity.lead_id == Lead.id)
        .filter(Opportunity.id.is_(None))
        .order_by(Lead.created_at.desc())
        .limit(200)
        .all()
    )

    # If lead_id was passed but already converted, block directly
    if request.method == "GET" and lead_from_qs and _lead_has_opportunity(lead_from_qs.id):
        flash("This lead is already converted to an opportunity.", "warning")
        return redirect(url_for("leads.view_lead", lead_id=lead_from_qs.id))

    if request.method == "POST":
        exp_close_raw = (request.form.get("expected_close_date") or "").strip()
        expected_close_date = (
            datetime.strptime(exp_close_raw, "%Y-%m-%d").date()
            if exp_close_raw else None
        )

        stage_id = request.form.get("stage_id")
        title = (request.form.get("title") or "").strip()
        company = (request.form.get("company") or "").strip()

        lead_id_form = (request.form.get("lead_id") or "").strip()
        selected_lead = Lead.query.get(int(lead_id_form)) if lead_id_form.isdigit() else None

        if selected_lead and _lead_has_opportunity(selected_lead.id):
            flash("This lead is already converted to an opportunity.", "warning")
            return redirect(url_for("leads.view_lead", lead_id=selected_lead.id))

        if not title:
            flash("Opportunity title is required.", "danger")
            return render_template(
                "pipeline/form.html",
                stages=stages,
                leads=leads,
                lead=selected_lead or lead_from_qs
            )

        linked_client_id = selected_lead.client_id if selected_lead else None
        linked_branch_id = selected_lead.branch_id if selected_lead else None

        if linked_client_id and linked_branch_id:
            branch_ok = ClientBranch.query.filter_by(
                id=linked_branch_id,
                client_id=linked_client_id
            ).first()
            if not branch_ok:
                flash("Selected lead has an invalid client/branch mapping.", "danger")
                return render_template(
                    "pipeline/form.html",
                    stages=stages,
                    leads=leads,
                    lead=selected_lead or lead_from_qs
                )

        default_stage = _get_stage_by_name("Qualification")
        chosen_stage_id = (
            int(stage_id)
            if (stage_id or "").isdigit()
            else (default_stage.id if default_stage else (stages[0].id if stages else None))
        )

        o = Opportunity(
            opp_code=_opp_code_next(),
            title=title,
            company=company,
            contact_name=(request.form.get("contact_name") or "").strip(),
            contact_email=(request.form.get("contact_email") or "").strip().lower(),
            contact_phone=(request.form.get("contact_phone") or "").strip(),
            expected_value=request.form.get("expected_value") or 0,
            expected_close_date=expected_close_date,
            notes=(request.form.get("notes") or "").strip(),
            lead_id=int(lead_id_form) if lead_id_form.isdigit() else None,
            client_id=linked_client_id,
            branch_id=linked_branch_id,
            owner_id=current_user.id,
            stage_id=chosen_stage_id,
        )

        db.session.add(o)
        db.session.flush()

        # Lock lead once converted
        if selected_lead:
            if hasattr(selected_lead, "is_converted"):
                selected_lead.is_converted = True
            if hasattr(selected_lead, "converted_at"):
                selected_lead.converted_at = datetime.utcnow()
            if hasattr(selected_lead, "converted_by_id"):
                selected_lead.converted_by_id = current_user.id

            converted_status = None
            if hasattr(selected_lead, "status") and selected_lead.status:
                converted_status = selected_lead.status
            if not converted_status and hasattr(selected_lead, "status_id"):
                # Try to set lead status to "Converted" if such master exists
                from ..models import LeadStatus
                converted_status = (
                    LeadStatus.query
                    .filter(func.lower(LeadStatus.name) == "converted")
                    .first()
                )
                if converted_status:
                    selected_lead.status_id = converted_status.id

        db.session.add(OpportunityStageHistory(
            opportunity_id=o.id,
            from_stage_id=None,
            to_stage_id=o.stage_id,
            changed_by_id=current_user.id,
            remark="Created from lead" if selected_lead else "Created"
        ))

        db.session.commit()

        flash("Opportunity created ✅", "success")
        return redirect(url_for("pipeline.board"))

    return render_template(
        "pipeline/form.html",
        stages=stages,
        leads=leads,
        lead=lead_from_qs
    )


@pipeline_bp.route("/<int:opp_id>/move", methods=["POST"])
@login_required
@require_perm("pipeline.move")
def move(opp_id):
    o = Opportunity.query.get_or_404(opp_id)
    _require_opp_access(o)

    to_stage_id = request.form.get("to_stage_id")
    if not (to_stage_id and to_stage_id.isdigit()):
        flash("Invalid stage.", "danger")
        return redirect(url_for("pipeline.board"))

    to_stage_id = int(to_stage_id)
    if o.stage_id == to_stage_id:
        return redirect(url_for("pipeline.board"))

    old = o.stage_id
    o.stage_id = to_stage_id
    o.updated_at = datetime.utcnow()

    db.session.flush()

    db.session.add(OpportunityStageHistory(
        opportunity_id=o.id,
        from_stage_id=old,
        to_stage_id=to_stage_id,
        changed_by_id=current_user.id,
        remark=(request.form.get("remark") or "").strip()
    ))

    db.session.commit()

    flash("Stage updated ✅", "success")
    return redirect(url_for("pipeline.board"))