import os
import uuid
from datetime import datetime
from decimal import Decimal

from flask import (
    Blueprint, render_template, request, redirect,
    url_for, flash, abort, jsonify, current_app
)
from flask_login import login_required, current_user
from sqlalchemy import create_engine, text, or_, func, extract

from app import db
from app.utils import require_perm
from app.models import Quote, Project, ProjectCost, QuoteStatus, CurrencyRateMaster, User, EmployeeProfile,Invoice

projects_bp = Blueprint("projects", __name__, url_prefix="/projects", template_folder="../templates")


def _clean(s):
    return (s or "").strip()

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 _quote_amount_without_tax(q):
    if not q:
        return Decimal("0")

    subtotal = _to_decimal(getattr(q, "subtotal", 0))
    discount = _to_decimal(getattr(q, "discount", 0))
    amount = subtotal - discount

    if amount < 0:
        amount = Decimal("0")

    return amount


def _get_rate_to_inr(currency_code, ref_date=None):
    currency_code = (currency_code or "INR").strip().upper()
    currency_code = {"EURO": "EUR", "EUROS": "EUR", "€": "EUR"}.get(currency_code, currency_code)

    if currency_code == "INR":
        return Decimal("1")

    if not ref_date:
        ref_date = datetime.utcnow().date()

    rate_row = (
        CurrencyRateMaster.query
        .filter(CurrencyRateMaster.currency_code == currency_code)
        .filter(CurrencyRateMaster.year == ref_date.year)
        .filter(CurrencyRateMaster.month == ref_date.month)
        .first()
    )

    if not rate_row:
        rate_row = (
            CurrencyRateMaster.query
            .filter(CurrencyRateMaster.currency_code == currency_code)
            .order_by(CurrencyRateMaster.year.desc(), CurrencyRateMaster.month.desc())
            .first()
        )

    if not rate_row:
        return Decimal("0")

    return _to_decimal(rate_row.rate_to_inr)


def _project_amount_without_tax(project):
    if getattr(project, "quote", None):
        return _quote_amount_without_tax(project.quote)

    return _to_decimal(project.contract_value)


def attach_project_value_display(projects):

    for p in projects:

        amount_ex_tax = _project_amount_without_tax(p)

        currency = (p.currency or "INR").strip().upper()

        bill_date = p.pms_bill_date.date() if isinstance(p.pms_bill_date, datetime) else p.pms_bill_date

        p.jobcard_bill_date_display = bill_date

        p.pms_bill_no_display = p.pms_bill_no

        ref_date = bill_date or (p.created_at.date() if p.created_at else datetime.utcnow().date())

        rate = _get_rate_to_inr(currency, ref_date)

        p.amount_ex_tax_display = amount_ex_tax

        p.amount_inr_display = amount_ex_tax * rate

        p.currency_rate_display = rate

    return projects

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

def _team_user_ids(manager_user_id: int, include_self: bool = True):
    seen = set()
    if include_self:
        seen.add(manager_user_id)

    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 and uid not in seen:
                seen.add(uid)
                stack.append(uid)

    return list(seen)





def _project_team_filter_users():
    visible_user_ids = _visible_project_user_ids()

    if visible_user_ids is None:
        return (
            User.query
            .filter(User.is_active == True)
            .order_by(User.name.asc())
            .all()
        )

    return (
        User.query
        .filter(User.id.in_(visible_user_ids))
        .filter(User.is_active == True)
        .order_by(User.name.asc())
        .all()
    )

def _visible_project_user_ids():
    if current_user.has_perm("projects.view_all"):
        return None

    return _team_user_ids(current_user.id, include_self=True)


def _project_scope_query():
    project_query = Project.query.outerjoin(Quote, Quote.id == Project.quote_id)

    visible_user_ids = _visible_project_user_ids()

    if visible_user_ids is None:
        return project_query

    if hasattr(Quote, "assigned_to_id"):
        return project_query.filter(
            or_(
                Quote.created_by_id.in_(visible_user_ids),
                Quote.assigned_to_id.in_(visible_user_ids),
                Project.created_by_id.in_(visible_user_ids)
            )
        )

    return project_query.filter(
        or_(
            Quote.created_by_id.in_(visible_user_ids),
            Project.created_by_id.in_(visible_user_ids)
        )
    )


def _project_team_filter_users():
    visible_user_ids = _visible_project_user_ids()

    if visible_user_ids is None:
        return User.query.filter_by(is_active=True).order_by(User.name.asc()).all()

    return (
        User.query
        .filter(User.id.in_(visible_user_ids))
        .filter(User.is_active == True)
        .order_by(User.name.asc())
        .all()
    )


from app.services.margin import get_margin_threshold_percent


def recompute_project_margin(project):
    contract = Decimal(str(project.contract_value or 0))
    total_cost = Decimal(str(project.total_cost or 0))

    margin_amt = contract - total_cost
    margin_pct = Decimal("0")
    if contract > 0:
        margin_pct = (margin_amt * Decimal("100")) / contract

    project.margin_amount = margin_amt
    project.margin_percent = margin_pct

    threshold = get_margin_threshold_percent()
    project.margin_flag = (margin_pct < threshold)

def attach_jobcard_details(projects):
    """
    Adds display fields from saved DB values.
    """
    for p in projects:
        p.jobcard_no_display = getattr(p, "jobcard_no", None)
        p.jobcard_status_display = getattr(p, "jobcard_status", None) or "Pending"
    return projects

def refresh_and_save_jobcard(project):
    old_jobcard_no = project.jobcard_no
    old_jobcard_status = project.jobcard_status or "Pending"
    old_bill_no = project.pms_bill_no
    old_bill_date = project.pms_bill_date

    details = fetch_jobcard_details_from_lms(project)

    new_jobcard_no = details.get("jobcard_no") or old_jobcard_no
    new_jobcard_status = details.get("jobcard_status") or old_jobcard_status or "Pending"

    bill_details = fetch_bill_details_from_lms(new_jobcard_no) if new_jobcard_no else {}

    new_bill_no = bill_details.get("bill_no") or old_bill_no
    new_bill_date = bill_details.get("bill_date") or old_bill_date

    changed = (
        str(old_jobcard_no or "") != str(new_jobcard_no or "")
        or str(old_jobcard_status or "") != str(new_jobcard_status or "")
        or str(old_bill_no or "") != str(new_bill_no or "")
        or str(old_bill_date or "") != str(new_bill_date or "")
    )

    project.jobcard_no = new_jobcard_no
    project.jobcard_status = new_jobcard_status
    project.pms_bill_no = new_bill_no
    project.pms_bill_date = new_bill_date
    project.jobcard_last_synced_at = datetime.utcnow()

    return changed, {
        "jobcard_no": project.jobcard_no,
        "jobcard_status": project.jobcard_status or "Pending",
        "pms_bill_no": project.pms_bill_no,
        "pms_bill_date": project.pms_bill_date,
    }

def save_project_file(file_obj):
    if not file_obj or not file_obj.filename:
        return None

    upload_root = os.path.join(current_app.root_path, "static", "uploads", "project_files")
    os.makedirs(upload_root, exist_ok=True)

    ext = os.path.splitext(file_obj.filename)[1]
    unique_name = f"{uuid.uuid4().hex}{ext}"
    abs_path = os.path.join(upload_root, unique_name)
    file_obj.save(abs_path)

    return f"uploads/project_files/{unique_name}"


def get_external_engine():
    external_uri = current_app.config.get("LMS_DB_URI")
    if not external_uri:
        raise Exception("LMS_DB_URI is not configured in config.")

    return create_engine(external_uri, pool_pre_ping=True)

def fetch_bill_details_from_lms(jobcard_no):
    result = {
        "bill_date": None,
        "bill_no": None,
    }

    if not jobcard_no:
        return result

    try:
        engine = get_external_engine()

        sql = text("""
            SELECT TOP 1
                BillNo,
                BillDate
            FROM dbo.TranslationBill
            WHERE JobCardNo = :jobcard_no
            ORDER BY BillDate DESC
        """)

        with engine.begin() as conn:
            row = conn.execute(sql, {
                "jobcard_no": str(jobcard_no).strip()
            }).mappings().first()

        if not row:
            return result

        bill_date = row.get("BillDate")
        if isinstance(bill_date, datetime):
            bill_date = bill_date.date()

        result["bill_no"] = row.get("BillNo")
        result["bill_date"] = bill_date

        return result

    except Exception:
        return result


def sync_project_to_lms(project):
    engine = get_external_engine()

    quote = project.quote
    quotation_title = quote.opportunity.title if quote and quote.opportunity else project.name
    client_name = project.client.company_name if project.client else None

    created_by_email = None
    if project.created_by:
        created_by_email = project.created_by.email

    insert_sql = text("""
        INSERT INTO dbo.LMSQuotation
        (
            QuotationNo,
            QuotationTitle,
            Amount,
            Currency,
            LMSUserName,
            DeliveryDate,
            SpecialInstructionsByClient,
            ProjectFileSharedBy,
            FileURL,
            PMSUserId,
            CreatedOn,
            Quotationid,
            ClientName,
            IsUsed,
            AddedBy,
            JobcardNo,
            AppType
        )
        OUTPUT INSERTED.Id
        VALUES
        (
            :quotation_no,
            :quotation_title,
            :amount,
            :currency,
            :lms_user_name,
            :delivery_date,
            :special_instructions,
            :project_file_shared_by,
            :file_url,
            :pms_user_id,
            :created_on,
            :quotationid,
            :client_name,
            :is_used,
            :added_by,
            :jobcard_no,
            :app_type
        )
    """)

    params = {
        "quotation_no": quote.quote_code if quote else None,
        "quotation_title": quotation_title,
        "amount": float(project.contract_value or 0),
        "currency": project.currency,
        "lms_user_name": created_by_email,
        "delivery_date": project.delivery_date,
        "special_instructions": project.special_instructions_by_client,
        "project_file_shared_by": project.project_file_shared_by,
        "file_url": project.file_url,
        "pms_user_id": str(project.created_by_id) if project.created_by_id else None,
        "created_on": datetime.utcnow(),
        "quotationid": quote.id if quote else None,
        "client_name": client_name,
        "is_used": False,
        "added_by": project.created_by_id,
        "jobcard_no": None,
        "app_type": "Crystal Nexus",
    }

    with engine.begin() as conn:
        inserted_id = conn.execute(insert_sql, params).scalar()

    return inserted_id


def fetch_jobcard_details_from_lms(project):
    """
    Fetch Jobcard No + Jobcard Status from LMS.

    Status source:
    jobcardMaster.IsBilled
        0 = In Process
        1 = Completed
        2 = Billed
    """
    result = {
        "jobcard_no": None,
        "jobcard_status": "Pending"
    }

    if not project:
        return result

    try:
        engine = get_external_engine()

        quote_code = None
        if getattr(project, "quote", None) and getattr(project.quote, "quote_code", None):
            quote_code = (project.quote.quote_code or "").strip()

        sql_lms_by_quotation_no = text("""
            SELECT TOP 1
                Id,
                QuotationNo,
                JobcardNo
            FROM dbo.LMSQuotation
            WHERE QuotationNo = :quotation_no
              AND AppType = :app_type
            ORDER BY Id DESC
        """)

        sql_lms_by_external_id = text("""
            SELECT TOP 1
                Id,
                QuotationNo,
                JobcardNo
            FROM dbo.LMSQuotation
            WHERE Id = :external_id
              AND AppType = :app_type
            ORDER BY Id DESC
        """)

        sql_lms_by_quote_id = text("""
            SELECT TOP 1
                Id,
                QuotationNo,
                JobcardNo
            FROM dbo.LMSQuotation
            WHERE Quotationid = :quotationid
              AND AppType = :app_type
            ORDER BY Id DESC
        """)

        sql_jobcard_by_jobcardno = text("""
            SELECT TOP 1
                JobCardNo,
                QuotationsNo,
                IsBilled
            FROM dbo.jobcardMaster
            WHERE JobCardNo = :jobcard_no
            ORDER BY JobCardNo DESC
        """)

        sql_jobcard_by_quotationno = text("""
            SELECT TOP 1
                JobCardNo,
                QuotationsNo,
                IsBilled
            FROM dbo.jobcardMaster
            WHERE QuotationsNo = :quotation_no
            ORDER BY JobCardNo DESC
        """)

        lms_row = None
        jobcard_row = None

        with engine.begin() as conn:
            if quote_code:
                lms_row = conn.execute(sql_lms_by_quotation_no, {
                    "quotation_no": quote_code,
                    "app_type": "Crystal Nexus"
                }).mappings().first()

            if not lms_row and getattr(project, "external_lmsquotation_id", None):
                lms_row = conn.execute(sql_lms_by_external_id, {
                    "external_id": project.external_lmsquotation_id,
                    "app_type": "Crystal Nexus"
                }).mappings().first()

            if not lms_row and getattr(project, "quote_id", None):
                lms_row = conn.execute(sql_lms_by_quote_id, {
                    "quotationid": project.quote_id,
                    "app_type": "Crystal Nexus"
                }).mappings().first()

            lms_jobcard_no = None
            if lms_row:
                raw_jobcard = lms_row.get("JobcardNo")
                if raw_jobcard is not None:
                    lms_jobcard_no = str(raw_jobcard).strip()
                    if lms_jobcard_no.lower() == "null" or lms_jobcard_no == "":
                        lms_jobcard_no = None

            if lms_jobcard_no:
                jobcard_row = conn.execute(sql_jobcard_by_jobcardno, {
                    "jobcard_no": lms_jobcard_no
                }).mappings().first()

            if not jobcard_row and quote_code:
                jobcard_row = conn.execute(sql_jobcard_by_quotationno, {
                    "quotation_no": quote_code
                }).mappings().first()

        if jobcard_row:
            raw_jobcard_no = jobcard_row.get("JobCardNo")
            jobcard_no = str(raw_jobcard_no).strip() if raw_jobcard_no is not None else None

            if jobcard_no and jobcard_no.lower() != "null":
                result["jobcard_no"] = jobcard_no

            raw_is_billed = jobcard_row.get("IsBilled")
            try:
                is_billed = int(raw_is_billed) if raw_is_billed is not None else None
            except Exception:
                is_billed = None

            if is_billed == 0:
                result["jobcard_status"] = "In Process"
            elif is_billed == 1:
                result["jobcard_status"] = "Completed"
            elif is_billed == 2:
                result["jobcard_status"] = "Billed"
            else:
                result["jobcard_status"] = "Pending"

            return result

        if lms_row:
            raw_jobcard = lms_row.get("JobcardNo")
            lms_jobcard_no = str(raw_jobcard).strip() if raw_jobcard is not None else None
            if lms_jobcard_no and lms_jobcard_no.lower() != "null":
                result["jobcard_no"] = lms_jobcard_no
                result["jobcard_status"] = "Pending"

        return result

    except Exception:
        return result
    
def save_jobcard_details_to_project(project, details):
    if not project:
        return

    project.jobcard_no = details.get("jobcard_no") or project.jobcard_no
    project.jobcard_status = details.get("jobcard_status") or project.jobcard_status or "Pending"

    bill_details = fetch_bill_details_from_lms(project.jobcard_no) if project.jobcard_no else {}

    bill_no = bill_details.get("bill_no")
    bill_date = bill_details.get("bill_date")

    if bill_no:
        project.pms_bill_no = bill_no

    if bill_date:
        project.pms_bill_date = bill_date

    project.jobcard_last_synced_at = datetime.utcnow()


def re_sync_project_to_lms(project):
    """
    Retry sync for an already-created project.
    Inserts again into LMSQuotation and updates sync metadata locally.
    """
    ext_id = sync_project_to_lms(project)

    project.external_lmsquotation_id = ext_id
    project.external_sync_status = "Success"
    project.external_sync_message = "Re-synced successfully"
    return ext_id

@projects_bp.route("/assign", methods=["GET", "POST"])
@login_required
@require_perm("projects.create")
def assign_project():
    is_admin_user = (
        current_user.has_perm("projects.view_all")
        or (getattr(getattr(current_user, "role", None), "name", "") or "").strip().lower()
        in ["admin", "system administrator", "super admin"]
    )

    # SHOW SENT + SELECTED QUOTES
    assignable_statuses = QuoteStatus.query.filter(
        QuoteStatus.name.in_(["Sent", "Selected"])
    ).all()

    assignable_status_ids = [s.id for s in assignable_statuses]
    sent_quotes = []
    assigned_projects = []
    sent_quotes = []
    assigned_projects = []
    if assignable_status_ids:
        quote_query = (
            Quote.query
            .filter(Quote.status_id.in_(assignable_status_ids))
            .outerjoin(Project, Project.quote_id == Quote.id)
            .filter(Project.id.is_(None))
        )

        # Normal users see only own / assigned quotes
        # Admin sees all quotes
        if not is_admin_user:
            if hasattr(Quote, "assigned_to_id"):
                quote_query = quote_query.filter(
                    or_(
                        Quote.created_by_id == current_user.id,
                        Quote.assigned_to_id == current_user.id
                    )
                )
            else:
                quote_query = quote_query.filter(
                    Quote.created_by_id == current_user.id
                )
        sent_quotes = quote_query.order_by(Quote.id.desc()).all()

    # PROJECT LIST BELOW
    project_query = Project.query.outerjoin(Quote, Quote.id == Project.quote_id)

    # Admin / users with projects.view_all can see all assigned projects
    if not is_admin_user:
        if hasattr(Quote, "assigned_to_id"):
            project_query = project_query.filter(
                or_(
                    Quote.created_by_id == current_user.id,
                    Quote.assigned_to_id == current_user.id,
                    Project.created_by_id == current_user.id
                )
            )
        else:
            project_query = project_query.filter(
                or_(
                    Quote.created_by_id == current_user.id,
                    Project.created_by_id == current_user.id
                )
            )

    assigned_projects = project_query.order_by(Project.id.desc()).limit(20).all()

    if request.method == "POST":
        quote_id = request.form.get("quote_id", type=int)
        delivery_date_raw = request.form.get("delivery_date")
        special_instructions = _clean(request.form.get("special_instructions_by_client"))
        file_url = _clean(request.form.get("file_url"))
        upload_file = request.files.get("project_file_shared_by")

        if not quote_id:
            flash("Please select quotation number.", "danger")
            return redirect(url_for("projects.assign_project"))

        quote = Quote.query.get_or_404(quote_id)

        if getattr(quote, "project", None):
            flash("Project already assigned for this quotation.", "warning")
            return redirect(url_for("projects.view_project", project_id=quote.project.id))

        if not quote.status or quote.status.name not in ("Selected", "Sent"):
            flash("Only Sent/Selected quotations can be assigned as project.", "danger")
            return redirect(url_for("projects.assign_project"))

        delivery_date = None
        if delivery_date_raw:
            try:
                delivery_date = datetime.strptime(delivery_date_raw, "%Y-%m-%dT%H:%M")
            except ValueError:
                flash("Invalid delivery date format.", "danger")
                return redirect(url_for("projects.assign_project"))

        uploaded_path = save_project_file(upload_file)
        project_name = quote.opportunity.title if quote.opportunity else f"Project for {quote.quote_code}"

        project = Project(
            project_code=_project_code_next(),
            name=project_name,
            quote_id=quote.id,
            client_id=quote.client_id,
            branch_id=quote.branch_id,
            currency=quote.currency or "INR",
            contract_value=_quote_amount_without_tax(quote),
            delivery_date=delivery_date,
            special_instructions_by_client=special_instructions or None,
            project_file_shared_by=uploaded_path,
            file_url=file_url or None,
            created_by_id=current_user.id,
            status="Active",
            external_sync_status="Pending",
            created_at=datetime.utcnow(),
        )

        recompute_project_margin(project)

        try:
            db.session.add(project)
            db.session.flush()

            ext_id = sync_project_to_lms(project)

            project.external_lmsquotation_id = ext_id
            project.external_sync_status = "Success"
            project.external_sync_message = "Synced successfully"

            details = fetch_jobcard_details_from_lms(project)
            save_jobcard_details_to_project(project, details)

            db.session.commit()

            flash("Project assigned and synced to LMS successfully.", "success")
            return redirect(url_for("projects.assign_project"))

        except Exception as e:
            db.session.rollback()
            flash(f"Failed to assign project: {str(e)}", "danger")
            return redirect(url_for("projects.assign_project"))

    assigned_projects = attach_project_value_display(assigned_projects)
    assigned_projects = attach_jobcard_details(assigned_projects)

    return render_template(
        "projects/assign_project.html",
        sent_quotes=sent_quotes,
        assigned_projects=assigned_projects
    )

@projects_bp.route("/<int:project_id>/refresh-jobcard", methods=["POST"])
@login_required
@require_perm("projects.view")
def refresh_project_jobcard(project_id):
    p = Project.query.get_or_404(project_id)

    try:
        changed, details = refresh_and_save_jobcard(p)
        db.session.commit()

        return jsonify({
            "ok": True,
            "project_id": p.id,
            "jobcard_no": p.jobcard_no,
            "jobcard_status": p.jobcard_status,
            "pms_bill_no": p.pms_bill_no,
            "pms_bill_date": p.pms_bill_date.strftime("%d-%m-%Y") if p.pms_bill_date else None,
            "changed": changed,
            "message": (
                "Jobcard updated successfully."
                if changed
                else "No change found."
            )
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "ok": False,
            "project_id": p.id,
            "message": str(e)
        }), 500
    
@projects_bp.route("/assigned", methods=["GET"])
@login_required
@require_perm("projects.view")
def assigned_projects_page():
    month = request.args.get("month", type=int)
    year = request.args.get("year", type=int)
    user_id = request.args.get("user_id", type=int)
    jobcard_no = _clean(request.args.get("jobcard_no"))
    jobcard_status = _clean(request.args.get("jobcard_status"))
    client_name = _clean(request.args.get("client_name"))

    today = datetime.utcnow().date()
    month = month or today.month
    year = year or today.year

    team_users = _project_team_filter_users()
    allowed_user_ids = _visible_project_user_ids()

    selected_user_id = user_id
    if selected_user_id and allowed_user_ids is not None and selected_user_id not in allowed_user_ids:
        selected_user_id = current_user.id

    project_query = _project_scope_query()

    if selected_user_id:
        selected_team_ids = _team_user_ids(selected_user_id, include_self=True)

        if hasattr(Quote, "assigned_to_id"):
            project_query = project_query.filter(or_(
                Quote.created_by_id.in_(selected_team_ids),
                Quote.assigned_to_id.in_(selected_team_ids),
                Project.created_by_id.in_(selected_team_ids)
            ))
        else:
            project_query = project_query.filter(or_(
                Quote.created_by_id.in_(selected_team_ids),
                Project.created_by_id.in_(selected_team_ids)
            ))

    all_projects = (
        project_query
        .order_by(Project.created_at.desc(), Project.id.desc())
        .all()
    )

    all_projects = attach_project_value_display(all_projects)
    all_projects = attach_jobcard_details(all_projects)

    quote_ids = [p.quote_id for p in all_projects if p.quote_id]
    invoice_map = {}

    if quote_ids:
        invoices = (
            Invoice.query
            .filter(Invoice.quote_id.in_(quote_ids))
            .filter(Invoice.status != "Cancelled")
            .order_by(Invoice.quote_id.asc(), Invoice.id.desc())
            .all()
        )

        for inv in invoices:
            if inv.quote_id not in invoice_map:
                invoice_map[inv.quote_id] = inv

    projects = []

    for p in all_projects:
        status = (p.jobcard_status or "Pending").strip()
        invoice = invoice_map.get(p.quote_id)

        p.cn_invoice = invoice
        p.cn_invoice_no = invoice.invoice_no if invoice else None
        p.cn_invoice_date = invoice.invoice_date if invoice else None
        p.cn_invoice_status = invoice.status if invoice else None
        p.cn_invoice_amount = Decimal(str(invoice.total_amount or 0)) if invoice else Decimal("0")

        # Month filter:
        # Prefer Crystal Nexus invoice date if invoice exists,
        # else PMS bill date if PMS billed,
        # else project created date.
        report_date = None

        if p.cn_invoice_date:
            report_date = p.cn_invoice_date
        elif status == "Billed":
            report_date = getattr(p, "jobcard_bill_date_display", None)
        elif p.created_at:
            report_date = p.created_at.date()

        if not (report_date and report_date.month == month and report_date.year == year):
            continue

        if jobcard_no:
            current_jobcard_no = str(p.jobcard_no or "").strip().lower()
            current_cn_invoice_no = str(p.cn_invoice_no or "").strip().lower()

            if (
                jobcard_no.lower() not in current_jobcard_no
                and jobcard_no.lower() not in current_cn_invoice_no
            ):
                continue

        if jobcard_status:
            current_status = (p.jobcard_status or "Pending").strip()
            if current_status != jobcard_status:
                continue

        if client_name:
            current_client = ""
            if p.client and p.client.company_name:
                current_client = p.client.company_name.strip().lower()

            if client_name.lower() not in current_client:
                continue

        projects.append(p)

    summary = {
        "total_projects": len(projects),
        "total_value": sum(
            (_to_decimal(getattr(p, "amount_inr_display", 0)) for p in projects),
            Decimal("0")
        ),
        "billed_value": sum(
            (
                _to_decimal(getattr(p, "amount_inr_display", 0))
                for p in projects
                if (p.jobcard_status or "").strip() == "Billed"
            ),
            Decimal("0")
        ),
        "cn_billed": 0,
        "cn_invoice_value": Decimal("0"),
        "pending": 0,
        "in_process": 0,
        "completed": 0,
        "billed": 0,
        "not_generated": 0,
        "synced": 0,
        "sync_failed": 0,
    }

    for p in projects:
        status = (p.jobcard_status or "Pending").strip()

        if p.jobcard_no:
            summary["synced"] += 1
        else:
            summary["not_generated"] += 1

        if (p.external_sync_status or "").lower() == "failed":
            summary["sync_failed"] += 1

        if p.cn_invoice:
            summary["cn_billed"] += 1
            summary["cn_invoice_value"] += _to_decimal(p.cn_invoice_amount)

        if status == "Billed":
            summary["billed"] += 1
        elif status == "Completed":
            summary["completed"] += 1
        elif status == "In Process":
            summary["in_process"] += 1
        else:
            summary["pending"] += 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 + 2))

    return render_template(
        "projects/assigned_projects.html",
        projects=projects,
        summary=summary,
        selected_month=month,
        selected_year=year,
        selected_user_id=selected_user_id,
        team_users=team_users,
        months=months,
        years=years,
        jobcard_no=jobcard_no,
        jobcard_status=jobcard_status,
        client_name=client_name,
    )

@projects_bp.route("/assigned/refresh", methods=["POST"])
@login_required
@require_perm("projects.view")
def refresh_assigned_projects_jobcards():
    month = request.form.get("month", type=int)
    year = request.form.get("year", type=int)
    user_id = request.form.get("user_id", type=int)

    today = datetime.utcnow().date()
    if not month:
        month = today.month
    if not year:
        year = today.year

    allowed_user_ids = _visible_project_user_ids()
    selected_user_id = user_id

    if selected_user_id:
        if allowed_user_ids is not None and selected_user_id not in allowed_user_ids:
            selected_user_id = current_user.id

    project_query = _project_scope_query()

    if selected_user_id:
        if hasattr(Quote, "assigned_to_id"):
            project_query = project_query.filter(
                or_(
                    Quote.created_by_id == selected_user_id,
                    Quote.assigned_to_id == selected_user_id,
                    Project.created_by_id == selected_user_id
                )
            )
        else:
            project_query = project_query.filter(
                or_(
                    Quote.created_by_id == selected_user_id,
                    Project.created_by_id == selected_user_id
                )
            )

    projects = project_query.order_by(Project.created_at.desc(), Project.id.desc()).all()
    

    changed_count = 0
    refreshed_count = 0

    try:
        for p in projects:
            changed, details = refresh_and_save_jobcard(p)
            refreshed_count += 1
            if changed:
                changed_count += 1

        db.session.commit()

        flash(
            f"Refreshed {refreshed_count} project(s). Updated {changed_count} changed record(s).",
            "success"
        )
    except Exception as e:
        db.session.rollback()
        flash(f"Failed to refresh assigned projects: {str(e)}", "danger")

    return redirect(url_for(
        "projects.assigned_projects_page",
        month=month,
        year=year,
        user_id=selected_user_id or ""
    ))

@projects_bp.route("/refresh-jobcards", methods=["POST"])
@login_required
@require_perm("projects.view")
def refresh_all_project_jobcards():
    project_query = Project.query.outerjoin(Quote, Quote.id == Project.quote_id)

    if hasattr(Quote, "assigned_to_id"):
        project_query = project_query.filter(
            or_(
                Quote.created_by_id == current_user.id,
                Quote.assigned_to_id == current_user.id,
                Project.created_by_id == current_user.id
            )
        )
    else:
        project_query = project_query.filter(
            or_(
                Quote.created_by_id == current_user.id,
                Project.created_by_id == current_user.id
            )
        )

    projects = project_query.order_by(Project.id.desc()).limit(50).all()

    results = []
    fetched_count = 0

    try:
        for p in projects:
            changed, details = refresh_and_save_jobcard(p)

            if p.jobcard_no:
                fetched_count += 1

            results.append({
                "project_id": p.id,
                "jobcard_no": p.jobcard_no,
                "jobcard_status": p.jobcard_status,
                "pms_bill_no": p.pms_bill_no,
                "pms_bill_date": p.pms_bill_date.strftime("%d-%m-%Y") if p.pms_bill_date else None,
                "changed": changed,
            })

        db.session.commit()

        return jsonify({
            "ok": True,
            "count": fetched_count,
            "results": results
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "ok": False,
            "message": str(e)
        }), 500
    
@projects_bp.route("/<int:project_id>/sync-lms", methods=["POST"])
@login_required
@require_perm("projects.view")
def sync_project_again(project_id):
    p = Project.query.get_or_404(project_id)

    try:
        re_sync_project_to_lms(p)

        details = fetch_jobcard_details_from_lms(p)
        save_jobcard_details_to_project(p, details)

        db.session.commit()
        flash("Project synced to LMS successfully.", "success")

    except Exception as e:
        db.session.rollback()
        p.external_sync_status = "Failed"
        p.external_sync_message = str(e)
        try:
            db.session.commit()
        except Exception:
            db.session.rollback()

        flash(f"Failed to sync project to LMS: {str(e)}", "danger")

    return redirect(url_for("projects.assign_project"))
    
@projects_bp.route("/quotation-details/<int:quote_id>")
@login_required
@require_perm("projects.create")
def quotation_details(quote_id):
    q = Quote.query.get_or_404(quote_id)

    amount_ex_tax = _quote_amount_without_tax(q)
    rate = _get_rate_to_inr(q.currency or "INR", datetime.utcnow().date())
    amount_inr = amount_ex_tax * rate

    return jsonify({
        "id": q.id,
        "quotation_no": q.quote_code,
        "quotation_title": q.opportunity.title if q.opportunity else "",
        "amount": str(amount_ex_tax),
        "currency": q.currency or "INR",
        "rate_to_inr": str(rate),
        "amount_inr": str(amount_inr),
    })


@projects_bp.route("/create-from-quote/<int:quote_id>", methods=["POST"])
@login_required
@require_perm("projects.create")
def create_from_quote(quote_id):
    q = Quote.query.get_or_404(quote_id)

    if not q.status or q.status.name not in ("Selected", "Sent"):
        flash("Project can be created only after Quote is Selected/Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if getattr(q, "project", None):
        flash("Project already exists for this quote.", "warning")
        return redirect(url_for("projects.view_project", project_id=q.project.id))

    p = Project(
        project_code=_project_code_next(),
        name=f"{q.opportunity.title} ({q.quote_code})",
        quote_id=q.id,
        client_id=q.client_id,
        branch_id=q.branch_id,
        currency=q.currency or "INR",
        contract_value=_quote_amount_without_tax(q),
        created_by_id=current_user.id,
        created_at=datetime.utcnow(),
        status="Active",
        external_sync_status="Pending",
        external_sync_message="Not synced yet"
    )
    recompute_project_margin(p)

    db.session.add(p)
    db.session.commit()

    flash("Project created ✅ You can sync it to LMS from Assign Project page.", "success")
    return redirect(url_for("projects.view_project", project_id=p.id))

@projects_bp.route("/<int:project_id>", methods=["GET", "POST"])
@login_required
@require_perm("projects.view")
def view_project(project_id):
    p = Project.query.get_or_404(project_id)

    # attach jobcard details for view page also
    p.jobcard_no_display = p.jobcard_no
    p.jobcard_status_display = p.jobcard_status or "Pending"

    if request.method == "POST":
        if not current_user.has_perm("projects.cost.add"):
            abort(403)

        cost_head = _clean(request.form.get("cost_head"))
        vendor = _clean(request.form.get("vendor_name"))
        notes = _clean(request.form.get("notes"))
        amt = _clean(request.form.get("amount")) or "0"
        cost_date = request.form.get("cost_date") or datetime.utcnow().date().isoformat()

        try:
            amt_dec = Decimal(amt)
        except Exception:
            amt_dec = Decimal("0")

        if not cost_head or amt_dec <= 0:
            flash("Cost Head and Amount (>0) are required.", "danger")
            return redirect(url_for("projects.view_project", project_id=p.id))

        try:
            parsed_cost_date = datetime.strptime(cost_date, "%Y-%m-%d").date()
        except ValueError:
            flash("Invalid cost date format.", "danger")
            return redirect(url_for("projects.view_project", project_id=p.id))

        c = ProjectCost(
            project_id=p.id,
            cost_date=parsed_cost_date,
            cost_head=cost_head,
            vendor_name=vendor or None,
            amount=amt_dec,
            notes=notes or None,
            created_by_id=current_user.id
        )
        db.session.add(c)

        p.total_cost = (Decimal(str(p.total_cost or 0)) + amt_dec)
        recompute_project_margin(p)

        db.session.commit()
        flash("Cost added ✅", "success")
        return redirect(url_for("projects.view_project", project_id=p.id))

    costs = p.costs.order_by(ProjectCost.cost_date.desc(), ProjectCost.id.desc()).all()
    return render_template("projects/project_view.html", project=p, costs=costs)


@projects_bp.route("/cost/<int:cost_id>/delete", methods=["POST"])
@login_required
@require_perm("projects.cost.delete")
def delete_cost(cost_id):
    c = ProjectCost.query.get_or_404(cost_id)
    p = c.project

    db.session.delete(c)
    db.session.flush()

    total = db.session.query(
        db.func.coalesce(db.func.sum(ProjectCost.amount), 0)
    ).filter(ProjectCost.project_id == p.id).scalar() or 0

    p.total_cost = Decimal(str(total))
    recompute_project_margin(p)

    db.session.commit()
    flash("Cost deleted ✅", "success")
    return redirect(url_for("projects.view_project", project_id=p.id))