from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.models.features import CoFounderProfile

cofounders_bp = Blueprint("cofounders", __name__, url_prefix="/cofounders")


@cofounders_bp.route("/")
@login_required
def index():
    skill_filter = request.args.get("skill", "").strip()
    profiles = CoFounderProfile.query.filter_by(is_visible=True).all()
    if skill_filter:
        profiles = [p for p in profiles if skill_filter.lower() in str(p.skills).lower()]
    all_skills = set()
    for p in CoFounderProfile.query.filter_by(is_visible=True).all():
        if p.skills:
            all_skills.update(p.skills)
    return render_template("cofounders/index.html", profiles=profiles, all_skills=sorted(all_skills), skill_filter=skill_filter)


@cofounders_bp.route("/profile", methods=["GET", "POST"])
@login_required
def my_profile():
    profile = CoFounderProfile.query.filter_by(user_id=current_user.id).first()
    if request.method == "POST":
        if not profile:
            profile = CoFounderProfile(user_id=current_user.id)
            db.session.add(profile)
        skills_raw = request.form.get("skills", "")
        profile.skills = [s.strip() for s in skills_raw.split(",") if s.strip()]
        interests_raw = request.form.get("interests", "")
        profile.interests = [i.strip() for i in interests_raw.split(",") if i.strip()]
        profile.experience_years = request.form.get("experience_years", 0, type=int)
        profile.bio = request.form.get("bio", "").strip()
        profile.looking_for = request.form.get("looking_for", "").strip()
        profile.city = request.form.get("city", "").strip()
        profile.is_visible = bool(request.form.get("is_visible"))
        db.session.commit()
        flash("Profile updated.", "success")
        return redirect(url_for("cofounders.index"))
    return render_template("cofounders/profile.html", profile=profile)
