from calendar import monthrange
from datetime import date, datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP

from flask import Blueprint, abort, flash, redirect, render_template, request, url_for, current_app
from flask_login import current_user, login_required
from sqlalchemy import func, or_
from werkzeug.utils import secure_filename
import os
import uuid

from app import db
from app.models import (
    LeadService, OperationsJobcard, OperationsJobcardService, Quote, QuoteItem, User, Opportunity,
    SoftwareResourceProfile, SoftwareVendor, SoftwareAssignment, SoftwareTimeEntry, SoftwareSubtask,
    SoftwareAMCContract, SoftwareSaaSSubscription, SoftwareSaaSBilling,
    SoftwareSaaSQuantityHistory, SoftwareSaaSAdjustment, SoftwareSaaSJobcardCost,
    Currency, CurrencyRateMaster, EmployeeProfile,
)
from app.utils import require_perm

software_bp = Blueprint("software", __name__, url_prefix="/software", template_folder="../templates")

SOFTWARE_CATEGORY = "software"
SAAS_SUBCATEGORY = "saas products"
CYCLE_MONTHS = {"MONTHLY": 1, "QUARTERLY": 3, "HALF_YEARLY": 6, "ANNUAL": 12}


def _d(v, default="0"):
    try:
        return Decimal(str(v if v not in (None, "") else default))
    except Exception:
        return Decimal(default)


def _currency_code(value):
    code = str(value or "INR").strip().upper()
    return {"EURO": "EUR", "EUROS": "EUR", "€": "EUR"}.get(code, code)


def _currency_to_inr_rate(currency_code, conversion_date=None):
    code = _currency_code(currency_code)
    if code == "INR":
        return Decimal("1")
    conversion_date = conversion_date or date.today()
    year, month = conversion_date.year, conversion_date.month
    lookup_codes = [code] if code != "EUR" else ["EUR", "EURO", "EUROS"]
    for candidate in lookup_codes:
        row = (CurrencyRateMaster.query
               .filter_by(year=year, month=month, currency_code=candidate)
               .order_by(CurrencyRateMaster.id.desc()).first())
        if row and _d(row.rate_to_inr) > 0:
            return _d(row.rate_to_inr)
    latest = None
    for candidate in lookup_codes:
        row = (CurrencyRateMaster.query.filter_by(currency_code=candidate)
               .order_by(CurrencyRateMaster.year.desc(), CurrencyRateMaster.month.desc(), CurrencyRateMaster.id.desc()).first())
        if row and (latest is None or (row.year, row.month, row.id) > (latest.year, latest.month, latest.id)):
            latest = row
    return _d(latest.rate_to_inr) if latest and _d(latest.rate_to_inr) > 0 else None


def _vendor_cost_snapshot(vendor, amount, conversion_date=None):
    currency = _currency_code(vendor.currency if vendor else "INR")
    rate = _currency_to_inr_rate(currency, conversion_date)
    if rate is None:
        return currency, None, None
    return currency, rate, (_d(amount) * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)


def _is_software_service(service):
    category = getattr(service, "category", None)
    return bool(category and (category.name or "").strip().lower() == SOFTWARE_CATEGORY)


def _software_jobcard(jobcard):
    return any(_is_software_service(row.service) for row in jobcard.services.all())


def _is_saas_item(item):
    service = getattr(item, "service", None)
    sub = getattr(service, "sub_category", None)
    return bool(_is_software_service(service) and sub and (sub.name or "").strip().lower() == SAAS_SUBCATEGORY)


def _add_months(d, months):
    m = d.month - 1 + months
    y = d.year + m // 12
    m = m % 12 + 1
    return date(y, m, min(d.day, monthrange(y, m)[1]))


def _period_for(subscription, billing_date):
    months = CYCLE_MONTHS.get((subscription.billing_cycle or "").upper(), 1)
    start = billing_date
    end = _add_months(start, months) - timedelta(days=1)
    return start, end


def _team_user_ids(manager_user_id):
    seen = 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 _can_view_all_saas():
    # Finance users who can generate PI/Invoice must see the complete upcoming
    # SaaS billing queue. Sales users without view-all remain restricted to
    # their own/reporting-team subscriptions.
    return any(current_user.has_perm(code) for code in (
        "software.saas.view_all", "invoices.view_all", "proforma.view_all",
        "quotes.view_all", "invoices.generate", "proforma.requests.view"
    ))


def _visible_subscription_query():
    q = SoftwareSaaSSubscription.query.join(Quote, SoftwareSaaSSubscription.source_quote_id == Quote.id)
    if _can_view_all_saas():
        return q
    allowed = list(set([current_user.id] + _team_user_ids(current_user.id)))
    return q.outerjoin(Opportunity, Quote.opportunity_id == Opportunity.id).filter(or_(
        Quote.created_by_id.in_(allowed), Opportunity.owner_id.in_(allowed)
    ))


def _require_subscription_access(sub):
    if _can_view_all_saas():
        return
    allowed = set([current_user.id] + _team_user_ids(current_user.id))
    owner_id = sub.source_quote.opportunity.owner_id if sub.source_quote and sub.source_quote.opportunity else None
    if not sub.source_quote or (sub.source_quote.created_by_id not in allowed and owner_id not in allowed):
        abort(403)


def _assignment_access(row):
    if current_user.has_perm("software.projects.view_all") or current_user.has_perm("software.assignment.manage"):
        return True
    if row.internal_resource and row.internal_resource.user_id == current_user.id:
        return True
    if row.external_vendor and row.external_vendor.linked_user_id == current_user.id:
        return True
    return False


def _save_saas_vendor_invoice(file_obj, jobcard_service_id):
    if not file_obj or not getattr(file_obj, "filename", None):
        return None, None
    original = secure_filename(file_obj.filename)
    if not original:
        return None, None
    ext = os.path.splitext(original)[1].lower()
    allowed = {".pdf", ".jpg", ".jpeg", ".png", ".doc", ".docx", ".xls", ".xlsx"}
    if ext not in allowed:
        raise ValueError("Vendor invoice must be PDF, image, Word, or Excel format.")
    relative_dir = os.path.join("uploads", "software", "saas_vendor_invoices", str(jobcard_service_id))
    absolute_dir = os.path.join(current_app.static_folder, relative_dir)
    os.makedirs(absolute_dir, exist_ok=True)
    filename = f"vendor_invoice_{uuid.uuid4().hex[:16]}{ext}"
    file_obj.save(os.path.join(absolute_dir, filename))
    return original, os.path.join(relative_dir, filename).replace(os.sep, "/")


def _logged_hours(assignment):
    return sum((_d(x.hours) for x in assignment.time_entries.all()), Decimal("0"))


def _estimated_cost(assignment):
    fixed = _d(assignment.fixed_cost)
    if fixed > 0:
        return fixed
    return _d(assignment.estimated_hours) * _d(assignment.hourly_cost)


def _actual_cost(assignment):
    hours = _logged_hours(assignment)
    fixed = _d(assignment.fixed_cost)
    # A fixed commercial cost is the committed assignment cost. Hourly work
    # accrues only from approved/logged hours.
    return fixed if fixed > 0 else (hours * _d(assignment.hourly_cost))


@software_bp.route("/")
@login_required
@require_perm("software.dashboard.view")
def dashboard():
    software_services = (
        OperationsJobcardService.query.join(LeadService, OperationsJobcardService.service_id == LeadService.id).all()
    )
    jobcard_ids = {x.jobcard_id for x in software_services if _is_software_service(x.service)}
    active_projects = OperationsJobcard.query.filter(OperationsJobcard.id.in_(jobcard_ids), ~OperationsJobcard.status.in_(["Completed", "Ready For Billing", "Sample Completed"])).count() if jobcard_ids else 0
    my_open = SoftwareAssignment.query.filter(SoftwareAssignment.status != "COMPLETED").all()
    my_open = sum(1 for x in my_open if _assignment_access(x))
    today = date.today()
    upcoming = SoftwareSaaSSubscription.query.filter(SoftwareSaaSSubscription.status == "ACTIVE", SoftwareSaaSSubscription.next_billing_date <= today + timedelta(days=30)).count()
    overdue = SoftwareSaaSSubscription.query.filter(SoftwareSaaSSubscription.status == "ACTIVE", SoftwareSaaSSubscription.next_billing_date < today).count()
    return render_template("software/dashboard.html", active_projects=active_projects, my_open=my_open, upcoming=upcoming, overdue=overdue)


@software_bp.route("/projects")
@login_required
@require_perm("software.projects.view")
def projects():
    rows = OperationsJobcard.query.order_by(OperationsJobcard.id.desc()).all()
    rows = [x for x in rows if _software_jobcard(x)]
    return render_template("software/projects.html", rows=rows)


@software_bp.route("/projects/<int:jobcard_id>")
@login_required
@require_perm("software.projects.view")
def project_detail(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    if not _software_jobcard(jobcard):
        abort(404)
    services = [x for x in jobcard.services.order_by(OperationsJobcardService.id.asc()).all() if _is_software_service(x.service)]
    assignments = SoftwareAssignment.query.filter(SoftwareAssignment.jobcard_service_id.in_([x.id for x in services])).order_by(SoftwareAssignment.id.desc()).all() if services else []
    resources = SoftwareResourceProfile.query.filter_by(is_active=True).all()
    vendors = SoftwareVendor.query.filter_by(is_active=True).order_by(SoftwareVendor.vendor_name.asc()).all()
    costs = {x.id: _actual_cost(x) for x in assignments}
    estimated_costs = {x.id: _estimated_cost(x) for x in assignments}
    logged_hours = {x.id: _logged_hours(x) for x in assignments}
    saas_items = [x.quote_item for x in services if x.quote_item and _is_saas_item(x.quote_item)]
    subtasks_by_assignment = {}
    if assignments:
        for st in (SoftwareSubtask.query.filter(SoftwareSubtask.assignment_id.in_([x.id for x in assignments]))
                   .order_by(SoftwareSubtask.id.asc()).all()):
            subtasks_by_assignment.setdefault(st.assignment_id, []).append(st)
    return render_template("software/project_detail.html", jobcard=jobcard, services=services, assignments=assignments, resources=resources, vendors=vendors, costs=costs, estimated_costs=estimated_costs, logged_hours=logged_hours, saas_items=saas_items, subtasks_by_assignment=subtasks_by_assignment)


@software_bp.route("/assign/<int:service_id>", methods=["POST"])
@login_required
@require_perm("software.assignment.manage")
def assign(service_id):
    svc = OperationsJobcardService.query.get_or_404(service_id)
    if not _is_software_service(svc.service):
        abort(400)
    target = (request.form.get("assignment_target_type") or "").upper()
    resource_id = request.form.get("internal_resource_id", type=int) if target == "INTERNAL" else None
    vendor_id = request.form.get("external_vendor_id", type=int) if target == "EXTERNAL" else None
    if target not in ("INTERNAL", "EXTERNAL") or (target == "INTERNAL" and not resource_id) or (target == "EXTERNAL" and not vendor_id):
        flash("Select a valid internal resource or external software vendor.", "danger")
        return redirect(url_for("software.project_detail", jobcard_id=svc.jobcard_id))
    default_rate = Decimal("0")
    if resource_id:
        default_rate = _d(SoftwareResourceProfile.query.get_or_404(resource_id).hourly_cost)
    if vendor_id:
        default_rate = _d(SoftwareVendor.query.get_or_404(vendor_id).hourly_rate)
    submitted_rate = _d(request.form.get("hourly_cost")) if request.form.get("hourly_cost") not in (None, "") else Decimal("0")
    # If a resource/vendor has a master rate, a blank or zero assignment rate
    # should inherit it instead of silently storing zero. A fixed-cost company
    # assignment can still legitimately have a zero hourly rate.
    effective_rate = submitted_rate if submitted_rate > 0 else default_rate
    row = SoftwareAssignment(
        jobcard_service_id=svc.id, assignment_target_type=target,
        internal_resource_id=resource_id, external_vendor_id=vendor_id,
        estimated_hours=_d(request.form.get("estimated_hours")),
        hourly_cost=effective_rate,
        fixed_cost=_d(request.form.get("fixed_cost")),
        start_date=datetime.strptime(request.form.get("start_date"), "%Y-%m-%d").date() if request.form.get("start_date") else None,
        deadline=datetime.strptime(request.form.get("deadline"), "%Y-%m-%dT%H:%M") if request.form.get("deadline") else None,
        instruction=(request.form.get("instruction") or "").strip() or None,
        assigned_by_id=current_user.id,
    )
    db.session.add(row)
    svc.status = "Assigned"
    db.session.commit()
    flash("Software work assigned successfully.", "success")
    return redirect(request.referrer or url_for("software.project_detail", jobcard_id=svc.jobcard_id))


@software_bp.route("/assignments/<int:assignment_id>/subtasks", methods=["POST"])
@login_required
@require_perm("software.assignment.manage")
def add_subtask(assignment_id):
    row = SoftwareAssignment.query.get_or_404(assignment_id)
    title = (request.form.get("title") or "").strip()
    if not title:
        flash("Subtask title is required.", "danger")
        return redirect(request.referrer or url_for("software.project_detail", jobcard_id=row.jobcard_service.jobcard_id))
    due_date = datetime.strptime(request.form.get("due_date"), "%Y-%m-%d").date() if request.form.get("due_date") else None
    priority = (request.form.get("priority") or "NORMAL").upper()
    if priority not in ("LOW", "NORMAL", "HIGH", "URGENT"):
        priority = "NORMAL"
    db.session.add(SoftwareSubtask(
        assignment_id=row.id, title=title,
        description=(request.form.get("description") or "").strip() or None,
        priority=priority, due_date=due_date, created_by_id=current_user.id
    ))
    db.session.commit()
    flash("Subtask added.", "success")
    return redirect(request.referrer or url_for("software.project_detail", jobcard_id=row.jobcard_service.jobcard_id))


@software_bp.route("/subtasks/<int:subtask_id>/status", methods=["POST"])
@login_required
@require_perm("software.time.create")
def update_subtask_status(subtask_id):
    subtask = SoftwareSubtask.query.get_or_404(subtask_id)
    row = subtask.assignment
    if not _assignment_access(row) and not current_user.has_perm("software.assignment.manage"):
        abort(403)
    status = (request.form.get("status") or "").upper()
    if status not in ("TODO", "IN_PROGRESS", "BLOCKED", "DONE"):
        flash("Invalid subtask status.", "danger")
        return redirect(request.referrer or url_for("software.my_work"))
    subtask.status = status
    subtask.completed_at = datetime.utcnow() if status == "DONE" else None
    if status == "IN_PROGRESS" and row.status == "ASSIGNED":
        row.status = "IN_PROGRESS"
    db.session.commit()
    flash("Subtask status updated.", "success")
    return redirect(request.referrer or url_for("software.my_work"))


@software_bp.route("/my-work")
@login_required
@require_perm("software.time.create")
def my_work():
    rows = SoftwareAssignment.query.order_by(SoftwareAssignment.status.asc(), SoftwareAssignment.deadline.asc(), SoftwareAssignment.id.desc()).all()
    rows = [x for x in rows if _assignment_access(x)]

    q = (request.args.get("q") or "").strip().lower()
    status = (request.args.get("status") or "").strip().upper()
    subtask_status = (request.args.get("subtask_status") or "").strip().upper()
    priority = (request.args.get("priority") or "").strip().upper()
    due = (request.args.get("due") or "").strip().lower()
    today = date.today()

    def _matches(row):
        svc = row.jobcard_service
        jc = svc.jobcard if svc else None
        client_name = (jc.client.company_name if jc and jc.client else "") or ""
        haystack = " ".join([
            jc.jobcard_code if jc else "",
            svc.service_name if svc else "",
            client_name,
            row.instruction or "",
            row.internal_resource.user.name if row.internal_resource and row.internal_resource.user else "",
            row.external_vendor.vendor_name if row.external_vendor else "",
        ]).lower()
        if q and q not in haystack:
            return False
        if status and row.status != status:
            return False

        subtasks = row.subtasks.order_by(SoftwareSubtask.id.asc()).all()
        if subtask_status and not any(st.status == subtask_status for st in subtasks):
            return False
        if priority and not any(st.priority == priority for st in subtasks):
            return False
        if due:
            dated = [st for st in subtasks if st.due_date and st.status != "DONE"]
            if due == "overdue" and not any(st.due_date < today for st in dated):
                return False
            if due == "today" and not any(st.due_date == today for st in dated):
                return False
            if due == "7days" and not any(today <= st.due_date <= today + timedelta(days=7) for st in dated):
                return False
            if due == "nodue" and not any(st.due_date is None and st.status != "DONE" for st in subtasks):
                return False
        return True

    filtered_rows = [x for x in rows if _matches(x)]
    summary = {
        "total": len(rows),
        "open": sum(1 for x in rows if x.status != "COMPLETED"),
        "in_progress": sum(1 for x in rows if x.status == "IN_PROGRESS"),
        "completed": sum(1 for x in rows if x.status == "COMPLETED"),
        "overdue": sum(1 for x in rows if x.deadline and x.deadline.date() < today and x.status != "COMPLETED"),
    }
    return render_template(
        "software/my_work.html", rows=filtered_rows, all_rows=rows, summary=summary,
        filters={"q": request.args.get("q", ""), "status": status, "subtask_status": subtask_status, "priority": priority, "due": due},
        SoftwareTimeEntry=SoftwareTimeEntry, SoftwareSubtask=SoftwareSubtask, today=today
    )


@software_bp.route("/assignments/<int:assignment_id>/time", methods=["POST"])
@login_required
@require_perm("software.time.create")
def add_time(assignment_id):
    row = SoftwareAssignment.query.get_or_404(assignment_id)
    if not _assignment_access(row):
        abort(403)
    hours = _d(request.form.get("hours"))
    description = (request.form.get("description") or "").strip()
    if hours <= 0 or hours > 24 or not description:
        flash("Enter valid hours and work description.", "danger")
        return redirect(request.referrer or url_for("software.my_work"))
    work_date = datetime.strptime(request.form.get("work_date"), "%Y-%m-%d").date() if request.form.get("work_date") else date.today()
    subtask_id = request.form.get("subtask_id", type=int)
    subtask = None
    if subtask_id:
        subtask = SoftwareSubtask.query.filter_by(id=subtask_id, assignment_id=row.id).first()
        if not subtask:
            flash("Invalid subtask selected.", "danger")
            return redirect(request.referrer or url_for("software.my_work"))
    db.session.add(SoftwareTimeEntry(assignment_id=row.id, subtask_id=(subtask.id if subtask else None), work_date=work_date, hours=hours, description=description, created_by_id=current_user.id))
    if subtask and subtask.status == "TODO":
        subtask.status = "IN_PROGRESS"
    if row.status == "ASSIGNED":
        row.status = "IN_PROGRESS"
    db.session.commit()
    flash("Time entry saved.", "success")
    return redirect(request.referrer or url_for("software.my_work"))


@software_bp.route("/assignments/<int:assignment_id>/complete", methods=["POST"])
@login_required
@require_perm("software.time.create")
def complete_assignment(assignment_id):
    row = SoftwareAssignment.query.get_or_404(assignment_id)
    if not _assignment_access(row):
        abort(403)
    logged_hours = _logged_hours(row)
    if logged_hours <= 0:
        flash("Work cannot be completed until at least one work-hour entry is logged.", "danger")
        return redirect(request.referrer or url_for("software.my_work"))
    open_subtasks = row.subtasks.filter(SoftwareSubtask.status != "DONE").count()
    if open_subtasks:
        flash("Complete all subtasks before marking the assignment complete.", "danger")
        return redirect(request.referrer or url_for("software.my_work"))
    row.status = "COMPLETED"
    row.completed_at = datetime.utcnow()
    row.completion_remark = (request.form.get("completion_remark") or "").strip() or None
    svc = row.jobcard_service
    others = SoftwareAssignment.query.filter(SoftwareAssignment.jobcard_service_id == svc.id, SoftwareAssignment.id != row.id, SoftwareAssignment.status != "COMPLETED").count()
    if not others:
        svc.status = "Completed"
        svc.completed_at = datetime.utcnow()
        svc.completed_quantity = svc.total_quantity or 0
    db.session.commit()
    flash("Assignment marked complete.", "success")
    return redirect(request.referrer or url_for("software.my_work"))


@software_bp.route("/projects/<int:jobcard_id>/close", methods=["POST"])
@login_required
@require_perm("software.jobcard.close")
def close_software_jobcard(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    if not _software_jobcard(jobcard): abort(400)
    services = [x for x in jobcard.services.all() if _is_software_service(x.service)]
    saas_billing = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first()
    saas_services = [x for x in services if x.quote_item and _is_saas_item(x.quote_item)]
    work_services = [x for x in services if x not in saas_services]
    if not services:
        flash("No Software service lines found.", "danger"); return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    for svc in saas_services:
        cost = SoftwareSaaSJobcardCost.query.filter_by(jobcard_service_id=svc.id).first()
        if not cost or not cost.vendor_id or _d(cost.vendor_cost) < 0:
            flash("Enter the Software vendor and vendor cost for every SaaS line before closure.", "danger"); return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
        if not cost.vendor_invoice_path:
            flash("Attach the vendor invoice for every SaaS line before closure.", "danger"); return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
        sub = SoftwareSaaSSubscription.query.filter_by(source_jobcard_id=jobcard.id, quote_item_id=svc.quote_item_id).first()
        if not sub:
            flash("Save the SaaS vendor and subscription details before closing this Jobcard.", "danger"); return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
        svc.status="Completed"; svc.completed_at=datetime.utcnow(); svc.completed_quantity=svc.total_quantity or 0
    for svc in work_services:
        rows=SoftwareAssignment.query.filter_by(jobcard_service_id=svc.id).all()
        if not rows:
            flash("Every Development / AMC line item must have at least one Software assignment before closure.","danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
        if any(x.status!="COMPLETED" for x in rows):
            flash("All Software assignments must be completed before the Jobcard can be closed.","danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
        svc.status="Completed"; svc.completed_at=svc.completed_at or datetime.utcnow(); svc.completed_quantity=svc.total_quantity or 0
    if saas_billing: saas_billing.status="READY_FOR_BILLING"
    jobcard.status="Ready For Billing"; jobcard.closed_by_id=current_user.id; jobcard.closed_at=datetime.utcnow()
    jobcard.closure_remark=(request.form.get("closure_remark") or "Software work completed").strip()
    jobcard.ready_for_billing_at=datetime.utcnow(); jobcard.ready_for_billing_by_id=current_user.id
    db.session.commit()
    flash("Software Jobcard closed and moved to Ready For Billing. Sales can now request PI through the normal Finance process.","success")
    return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))


@software_bp.route("/vendors", methods=["GET", "POST"])
@login_required
@require_perm("software.vendors.manage")
def vendors():
    if request.method == "POST":
        selected_currency = _currency_code(request.form.get("currency") or "INR")
        currency_row = Currency.query.filter(
            func.upper(Currency.code) == selected_currency,
            Currency.is_active.is_(True)
        ).first()
        if not currency_row:
            flash("Select a valid currency from Currency Master.", "danger")
            return redirect(url_for("software.vendors"))
        row = SoftwareVendor(
            vendor_name=(request.form.get("vendor_name") or "").strip(), vendor_type=(request.form.get("vendor_type") or "COMPANY").upper(),
            contact_person=(request.form.get("contact_person") or "").strip() or None, email=(request.form.get("email") or "").strip() or None,
            phone=(request.form.get("phone") or "").strip() or None, currency=selected_currency,
            hourly_rate=(Decimal("0") if (request.form.get("vendor_type") or "COMPANY").upper() == "COMPANY" else _d(request.form.get("hourly_rate"))), linked_user_id=request.form.get("linked_user_id", type=int),
            company_name=(request.form.get("company_name") or "").strip() or None, gstin=(request.form.get("gstin") or "").strip() or None,
            pan=(request.form.get("pan") or "").strip() or None, payment_terms=(request.form.get("payment_terms") or "").strip() or None,
        )
        if not row.vendor_name:
            flash("Vendor name is required.", "danger")
        else:
            db.session.add(row); db.session.commit(); flash("Software vendor added.", "success")
        return redirect(url_for("software.vendors"))
    rows = SoftwareVendor.query.order_by(SoftwareVendor.vendor_name.asc()).all()
    users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    currencies = Currency.query.filter_by(is_active=True).order_by(Currency.sort_order.asc(), Currency.code.asc()).all()
    return render_template("software/vendors.html", rows=rows, users=users, currencies=currencies)


@software_bp.route("/resources", methods=["GET", "POST"])
@login_required
@require_perm("software.resources.manage")
def resources():
    if request.method == "POST":
        user_id = request.form.get("user_id", type=int)
        row = SoftwareResourceProfile.query.filter_by(user_id=user_id).first() if user_id else None
        if row:
            row.role_type=(request.form.get("role_type") or "").strip() or None; row.hourly_cost=_d(request.form.get("hourly_cost")); row.skills=(request.form.get("skills") or "").strip() or None
        elif user_id:
            db.session.add(SoftwareResourceProfile(user_id=user_id, role_type=(request.form.get("role_type") or "").strip() or None, hourly_cost=_d(request.form.get("hourly_cost")), skills=(request.form.get("skills") or "").strip() or None))
        else:
            flash("Select a user.", "danger"); return redirect(url_for("software.resources"))
        db.session.commit(); flash("Software resource saved.", "success"); return redirect(url_for("software.resources"))
    rows = SoftwareResourceProfile.query.order_by(SoftwareResourceProfile.id.desc()).all()
    users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    return render_template("software/resources.html", rows=rows, users=users)


@software_bp.route("/jobcards/<int:jobcard_id>/saas/<int:service_id>/cost", methods=["POST"])
@login_required
@require_perm("software.saas.manage")
def save_saas_jobcard_cost(jobcard_id, service_id):
    jobcard=OperationsJobcard.query.get_or_404(jobcard_id); svc=OperationsJobcardService.query.get_or_404(service_id)
    if svc.jobcard_id!=jobcard.id or not svc.quote_item or not _is_saas_item(svc.quote_item): abort(400)
    if jobcard.status in ("Ready For Billing", "Completed") or jobcard.closed_at:
        flash("This SaaS Jobcard is closed. Vendor, subscription and commercial fields are locked.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    row=SoftwareSaaSJobcardCost.query.filter_by(jobcard_service_id=svc.id).first()
    if not row: row=SoftwareSaaSJobcardCost(jobcard_service_id=svc.id); db.session.add(row)
    vendor_id=request.form.get("vendor_id",type=int); vendor=SoftwareVendor.query.get_or_404(vendor_id) if vendor_id else None
    if not vendor or not vendor.is_active:
        flash("Select an active Software vendor.","danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
    row.vendor_id=vendor_id; row.vendor_cost=_d(request.form.get("vendor_cost"))
    currency,fx,cost_inr=_vendor_cost_snapshot(vendor,row.vendor_cost,getattr(jobcard,"created_at",None) or date.today())
    if fx is None:
        flash("Currency rate is not configured for %s in Currency Rate Master."%currency,"danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
    row.vendor_currency=currency; row.conversion_rate_to_inr=fx; row.vendor_cost_inr=cost_inr
    row.notes=(request.form.get("notes") or "").strip() or None; row.updated_by_id=current_user.id
    upload=request.files.get("vendor_invoice")
    if upload and upload.filename:
        try: original,path=_save_saas_vendor_invoice(upload,svc.id)
        except ValueError as exc:
            flash(str(exc),"danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
        row.vendor_invoice_original_name=original; row.vendor_invoice_path=path
    item=svc.quote_item; cycle=(request.form.get("billing_cycle") or item.billing_cycle or "MONTHLY").upper()
    if cycle not in CYCLE_MONTHS:
        flash("Select Monthly, Quarterly, Half-Yearly or Annual billing.","danger"); return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))
    raw=request.form.get("subscription_start_date"); sub_start=datetime.strptime(raw,"%Y-%m-%d").date() if raw else (jobcard.submitted_at or jobcard.created_at or datetime.utcnow()).date()
    qty=_d(request.form.get("current_quantity"),str(svc.total_quantity or item.qty or 1)); sell=_d(request.form.get("selling_rate"),str(item.rate or 0))
    vendor_unit=(row.vendor_cost/qty).quantize(Decimal("0.0001"),rounding=ROUND_HALF_UP) if qty>0 else Decimal("0")
    sub=SoftwareSaaSSubscription.query.filter_by(source_jobcard_id=jobcard.id,quote_item_id=item.id).first()
    created=False
    if not sub:
        sub=SoftwareSaaSSubscription(source_jobcard_id=jobcard.id,source_quote_id=jobcard.quote_id,quote_item_id=item.id,client_id=jobcard.client_id,branch_id=jobcard.branch_id,product_name=item.item_name,billing_cycle=cycle,subscription_start_date=sub_start,next_billing_date=None,current_quantity=qty,selling_rate=sell,currency=getattr(jobcard.quote,"currency","INR") or "INR",pro_rata_enabled=True,default_vendor_id=vendor.id,default_vendor_rate=vendor_unit,status="PENDING_FIRST_INVOICE",created_by_id=current_user.id)
        db.session.add(sub); created=True
    elif sub.status=="PENDING_FIRST_INVOICE":
        sub.billing_cycle=cycle; sub.subscription_start_date=sub_start; sub.current_quantity=qty; sub.selling_rate=sell; sub.default_vendor_id=vendor.id; sub.default_vendor_rate=vendor_unit; sub.pro_rata_enabled=True
    db.session.commit()
    flash("SaaS vendor details saved and subscription %s." % ("created" if created else "updated"),"success")
    return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard.id))


@software_bp.route("/saas")
@login_required
@require_perm("software.saas.view")
def saas_subscriptions():
    rows=(_visible_subscription_query().filter(SoftwareSaaSSubscription.status.in_(["ACTIVE","DEACTIVATED"]))
          .order_by(SoftwareSaaSSubscription.next_billing_date.asc(),SoftwareSaaSSubscription.id.desc()).all())
    return render_template("software/saas_subscriptions.html",rows=rows,today=date.today(),can_view_all=_can_view_all_saas())

@software_bp.route("/saas/create/<int:jobcard_id>/<int:quote_item_id>",methods=["GET","POST"])
@login_required
@require_perm("software.saas.manage")
def create_subscription(jobcard_id,quote_item_id):
    existing=SoftwareSaaSSubscription.query.filter_by(source_jobcard_id=jobcard_id,quote_item_id=quote_item_id).first()
    if existing: return redirect(url_for("software.saas_subscription_detail",subscription_id=existing.id))
    flash("SaaS subscriptions are created automatically when vendor details are saved on the initial SaaS Jobcard.","info")
    return redirect(url_for("operations.view_jobcard",jobcard_id=jobcard_id))

@software_bp.route("/saas/<int:subscription_id>")
@login_required
@require_perm("software.saas.view")
def saas_subscription_detail(subscription_id):
    sub=SoftwareSaaSSubscription.query.get_or_404(subscription_id); _require_subscription_access(sub)
    billings=sub.billings.order_by(SoftwareSaaSBilling.billing_date.desc()).all()
    first_invoice = None
    if sub.first_invoice_id:
        from app.models import Invoice
        first_invoice = Invoice.query.get(sub.first_invoice_id)
    changes=SoftwareSaaSQuantityHistory.query.filter_by(subscription_id=sub.id).order_by(SoftwareSaaSQuantityHistory.effective_date.desc(),SoftwareSaaSQuantityHistory.id.desc()).all()
    return render_template("software/saas_subscription_detail.html",sub=sub,billings=billings,changes=changes,first_invoice=first_invoice)

@software_bp.route("/saas/<int:subscription_id>/quantity",methods=["POST"])
@login_required
@require_perm("software.saas.manage")
def update_saas_quantity(subscription_id):
    sub=SoftwareSaaSSubscription.query.get_or_404(subscription_id); _require_subscription_access(sub)
    if sub.status!="ACTIVE": flash("User/licence count can be changed only for an active subscription.","danger"); return redirect(url_for("software.saas_subscriptions"))
    old=_d(sub.current_quantity); new=_d(request.form.get("new_quantity"),str(old))
    if new<0: flash("User/licence count cannot be negative.","danger"); return redirect(url_for("software.saas_subscriptions"))
    raw=request.form.get("effective_date"); eff=datetime.strptime(raw,"%Y-%m-%d").date() if raw else date.today()
    if sub.last_invoice_date and eff<sub.last_invoice_date: flash("Effective date cannot be before the last SaaS invoice date.","danger"); return redirect(url_for("software.saas_subscriptions"))
    if sub.next_billing_date and eff>=sub.next_billing_date: flash("For pro-rata adjustment, the effective date must be before the next billing date.","danger"); return redirect(url_for("software.saas_subscriptions"))
    if new==old: flash("There is no change in user/licence count.","info"); return redirect(url_for("software.saas_subscriptions"))
    db.session.add(SoftwareSaaSQuantityHistory(subscription_id=sub.id,old_quantity=old,new_quantity=new,effective_date=eff,reason=(request.form.get("reason") or "User/licence count updated").strip(),changed_by_id=current_user.id))
    sub.current_quantity=new; db.session.commit()
    flash("User/licence count updated. The next bill will include the pro-rata adjustment and future bills will use the new quantity.","success")
    return redirect(url_for("software.saas_subscriptions"))

@software_bp.route("/saas/<int:subscription_id>/deactivate",methods=["POST"])
@login_required
@require_perm("software.saas.manage")
def deactivate_saas_subscription(subscription_id):
    sub=SoftwareSaaSSubscription.query.get_or_404(subscription_id); _require_subscription_access(sub)
    for bill in SoftwareSaaSBilling.query.filter_by(subscription_id=sub.id).filter(SoftwareSaaSBilling.status.notin_(["INVOICED","CANCELLED"])).all():
        if not bill.invoice_id: bill.status="CANCELLED"
    sub.status="DEACTIVATED"; sub.next_billing_date=None; sub.deactivated_at=datetime.utcnow(); sub.deactivated_by_id=current_user.id; sub.deactivation_reason=(request.form.get("reason") or "Deactivated by Sales").strip()
    db.session.commit(); flash("SaaS subscription deactivated. No future billing will be created.","success")
    return redirect(url_for("software.saas_subscriptions"))

def _pending_prorata(sub,billing_id,rate):
    if not sub.last_invoice_date or not sub.next_billing_date: return Decimal("0")
    pstart=sub.last_invoice_date; pend=sub.next_billing_date-timedelta(days=1); days=max(1,(pend-pstart).days+1); total=Decimal("0")
    changes=(SoftwareSaaSQuantityHistory.query.filter_by(subscription_id=sub.id,billed_in_billing_id=None).filter(SoftwareSaaSQuantityHistory.effective_date>=pstart,SoftwareSaaSQuantityHistory.effective_date<=pend).order_by(SoftwareSaaSQuantityHistory.effective_date.asc(),SoftwareSaaSQuantityHistory.id.asc()).all())
    for c in changes:
        delta=_d(c.new_quantity)-_d(c.old_quantity); billdays=(pend-c.effective_date).days+1
        amount=(delta*rate*Decimal(billdays)/Decimal(days)).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)
        db.session.add(SoftwareSaaSAdjustment(billing_id=billing_id,quantity_delta=delta,effective_date=c.effective_date,days_billable=billdays,days_in_period=days,rate=rate,amount=amount,remarks=c.reason or "Pro-rata quantity adjustment",created_by_id=current_user.id)); total+=amount
    return total.quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)

@software_bp.route("/saas/<int:subscription_id>/request-invoice",methods=["POST"])
@login_required
@require_perm("software.saas.manage")
def request_saas_invoice(subscription_id):
    sub=SoftwareSaaSSubscription.query.get_or_404(subscription_id); _require_subscription_access(sub)
    if sub.status!="ACTIVE" or not sub.next_billing_date: flash("Only active subscriptions with an upcoming billing date can be requested.","danger"); return redirect(url_for("software.saas_subscriptions"))
    existing=SoftwareSaaSBilling.query.filter_by(subscription_id=sub.id,billing_date=sub.next_billing_date).filter(SoftwareSaaSBilling.status!="CANCELLED").first()
    if existing:
        flash("This billing cycle has already been requested.","info")
        return redirect(url_for("operations.view_jobcard",jobcard_id=existing.jobcard_id)) if existing.jobcard_id else redirect(url_for("software.saas_subscriptions"))
    qty=_d(sub.current_quantity); rate=_d(sub.selling_rate); bdate=sub.next_billing_date; pstart,pend=_period_for(sub,bdate); base=(qty*rate).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)
    vunit=_d(sub.default_vendor_rate); vcost=(qty*vunit).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP); vcur,fx,vcostinr=_vendor_cost_snapshot(sub.default_vendor,vcost,bdate) if sub.default_vendor else (None,None,None)
    if sub.default_vendor and fx is None: flash("Currency rate is not configured for %s for the upcoming billing month."%vcur,"danger"); return redirect(url_for("software.saas_subscriptions"))
    bill=SoftwareSaaSBilling(subscription_id=sub.id,period_start=pstart,period_end=pend,billing_date=bdate,base_quantity=qty,final_quantity=qty,unit_rate=rate,base_amount=base,pro_rata_amount=0,total_amount=base,vendor_id=sub.default_vendor_id,vendor_quantity=qty,vendor_rate=vunit,vendor_cost=vcost,vendor_currency=vcur,conversion_rate_to_inr=fx,vendor_cost_inr=vcostinr,status="REQUESTED",reviewed_by_id=current_user.id,reviewed_at=datetime.utcnow())
    db.session.add(bill); db.session.flush(); prorata=_pending_prorata(sub,bill.id,rate) if sub.pro_rata_enabled else Decimal("0"); bill.pro_rata_amount=prorata; bill.total_amount=(base+prorata).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)
    vendor_prorata=Decimal("0")
    if vunit>0:
        for adj in bill.adjustments.all(): vendor_prorata += _d(adj.quantity_delta)*vunit*Decimal(adj.days_billable)/Decimal(max(1,adj.days_in_period))
        bill.vendor_cost=(vcost+vendor_prorata.quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)).quantize(Decimal("0.01"),rounding=ROUND_HALF_UP)
        if sub.default_vendor: bill.vendor_currency,bill.conversion_rate_to_inr,bill.vendor_cost_inr=_vendor_cost_snapshot(sub.default_vendor,bill.vendor_cost,bdate)
    from app.operations.routes import _jobcard_code_next
    source=sub.source_jobcard; jc=OperationsJobcard(jobcard_code=_jobcard_code_next(),quote_id=sub.source_quote_id,client_id=sub.client_id,branch_id=sub.branch_id,assigned_to_id=source.assigned_to_id,assigned_by_id=current_user.id,current_owner_id=source.current_owner_id or source.assigned_to_id,status="Ready For Billing",submitted_at=datetime.utcnow(),closed_at=datetime.utcnow(),closed_by_id=current_user.id,closure_remark="Recurring SaaS billing cycle",ready_for_billing_at=datetime.utcnow(),ready_for_billing_by_id=current_user.id,client_deadline=datetime.combine(bdate,datetime.min.time()),billing_company_branch_id=source.billing_company_branch_id)
    db.session.add(jc); db.session.flush(); svc=OperationsJobcardService(jobcard_id=jc.id,quote_item_id=sub.quote_item_id,service_id=sub.quote_item.service_id,service_name=sub.quote_item.service.name if sub.quote_item.service else sub.product_name,status="Completed",total_quantity=qty,completed_quantity=qty,completed_at=datetime.utcnow(),vendor_name=sub.default_vendor.vendor_name if sub.default_vendor else None,vendor_rate=vunit,vendor_wordcount=0); db.session.add(svc); db.session.flush()
    if sub.default_vendor: db.session.add(SoftwareSaaSJobcardCost(jobcard_service_id=svc.id,vendor_id=sub.default_vendor_id,vendor_cost=bill.vendor_cost,vendor_currency=bill.vendor_currency,conversion_rate_to_inr=bill.conversion_rate_to_inr,vendor_cost_inr=bill.vendor_cost_inr,notes="Recurring SaaS cost snapshot",updated_by_id=current_user.id))
    bill.jobcard_id=jc.id; bill.status="READY_FOR_BILLING"; q=sub.source_quote; q.pi_request_status="Pending"; q.pi_requested_at=datetime.utcnow(); q.pi_requested_by_id=current_user.id; q.pi_request_note="Recurring SaaS billing: %s"%sub.product_name; q.pi_requested_jobcard_id=jc.id; q.invoice_request_status=None; q.invoice_requested_jobcard_id=None
    db.session.commit(); flash("Recurring SaaS billing requested. A Ready For Billing Jobcard was created and PI request sent to Finance.","success")
    return redirect(url_for("operations.view_jobcard",jobcard_id=jc.id))
