from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
from flask_login import login_required, current_user
from app.extensions import db
from app.models.contract import Contract
from app.models.lv import LVPosition
from datetime import datetime

contracts_bp = Blueprint('contracts', __name__)

def _vertrag_berechtigt():
    if current_user.is_superadmin():
        return True
    if current_user.is_firmadmin() or current_user.darf_lv_verwalten:
        return True
    return False

@contracts_bp.route('/')
@login_required
def index():
    if current_user.is_superadmin():
        contracts = Contract.query.order_by(Contract.name).all()
    else:
        contracts = Contract.query.filter_by(
            company_id=current_user.company_id
        ).order_by(Contract.name).all()
    return render_template('contracts/index.html', contracts=contracts, titel='Verträge')

@contracts_bp.route('/neu', methods=['GET', 'POST'])
@login_required
def neu():
    if not _vertrag_berechtigt():
        flash('Keine Berechtigung.', 'danger')
        return redirect(url_for('contracts.index'))
    if request.method == 'POST':
        c = Contract(
            company_id=current_user.company_id,
            name=request.form.get('name', '').strip(),
            belegnummer=request.form.get('belegnummer', '').strip(),
            beleg_datum=_parse_date(request.form.get('beleg_datum')),
            laufzeit_start=_parse_date(request.form.get('laufzeit_start')),
            laufzeit_ende=_parse_date(request.form.get('laufzeit_ende')),
            status=request.form.get('status', 'NEU'),
        )
        db.session.add(c)
        db.session.commit()
        flash(f'Vertrag "{c.name}" angelegt.', 'success')
        return redirect(url_for('contracts.index'))
    return render_template('contracts/neu.html', titel='Neuer Vertrag')

@contracts_bp.route('/<int:contract_id>')
@login_required
def detail(contract_id):
    c = Contract.query.get_or_404(contract_id)
    if c.company_id != current_user.company_id and not current_user.is_superadmin():
        return 'Zugriff verweigert', 403
    lv_names = db.session.query(LVPosition.lv_name).filter_by(
        company_id=current_user.company_id, contract_id=contract_id
    ).distinct().order_by(LVPosition.lv_name).all()
    lv_names = [r[0] for r in lv_names]
    return render_template('contracts/detail.html', contract=c, lv_names=lv_names, titel=c.name)

@contracts_bp.route('/<int:contract_id>/status', methods=['POST'])
@login_required
def status_set(contract_id):
    c = Contract.query.get_or_404(contract_id)
    if c.company_id != current_user.company_id and not current_user.is_superadmin():
        return 'Zugriff verweigert', 403
    if not _vertrag_berechtigt():
        flash('Keine Berechtigung.', 'danger')
        return redirect(url_for('contracts.index'))
    c.status = request.form.get('status', c.status)
    db.session.commit()
    flash('Status aktualisiert.', 'success')
    return redirect(url_for('contracts.detail', contract_id=contract_id))

@contracts_bp.route('/<int:contract_id>/update', methods=['POST'])
@login_required
def detail_update(contract_id):
    c = Contract.query.get_or_404(contract_id)
    if c.company_id != current_user.company_id and not current_user.is_superadmin():
        return 'Zugriff verweigert', 403
    if not _vertrag_berechtigt():
        flash('Keine Berechtigung.', 'danger')
        return redirect(url_for('contracts.index'))
    c.belegnummer = request.form.get('belegnummer', '').strip()
    c.beleg_datum = _parse_date(request.form.get('beleg_datum'))
    c.laufzeit_start = _parse_date(request.form.get('laufzeit_start'))
    c.laufzeit_ende = _parse_date(request.form.get('laufzeit_ende'))
    c.status = request.form.get('status', c.status)
    db.session.commit()
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.accept_mimetypes.best == 'application/json':
        return jsonify({'ok': True})
    flash('Vertrag aktualisiert.', 'success')
    return redirect(url_for('contracts.detail', contract_id=contract_id))

@contracts_bp.route('/<int:contract_id>/loeschen', methods=['POST'])
@login_required
def delete(contract_id):
    c = Contract.query.get_or_404(contract_id)
    if c.company_id != current_user.company_id and not current_user.is_superadmin():
        return 'Zugriff verweigert', 403
    if not _vertrag_berechtigt():
        flash('Keine Berechtigung.', 'danger')
        return redirect(url_for('contracts.index'))
    db.session.delete(c)
    db.session.commit()
    flash('Vertrag gelöscht.', 'success')
    return redirect(url_for('contracts.index'))

@contracts_bp.route('/api/lv-names')
@login_required
def api_lv_names():
    contract_id = request.args.get('contract_id', type=int)
    q = db.session.query(LVPosition.lv_name).filter_by(company_id=current_user.company_id)
    if contract_id:
        q = q.filter_by(contract_id=contract_id)
    names = [r[0] for r in q.distinct().order_by(LVPosition.lv_name).all()]
    return jsonify(names)

def _parse_date(s):
    if not s:
        return None
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%Y.%m.%d'):
        try:
            return datetime.strptime(s.strip(), fmt).date()
        except ValueError:
            continue
    return None
