"""Match seekers to jobs for job alert distribution."""
from ats.cv_parser import extract_skills_from_text, extract_text_from_cv

PROFILE_TEXT_FIELDS = (
    'skills', 'bio', 'education', 'experience_summary', 'qualification', 'headline',
)


def _job_text(job):
    return ' '.join([
        job.requirements or '',
        job.description or '',
        job.responsibilities or '',
        job.nice_to_have or '',
    ]).lower()


def _job_requirements(job):
    items = []
    for field in ('requirements', 'nice_to_have', 'responsibilities'):
        value = getattr(job, field, '') or ''
        items.extend(line.strip() for line in value.splitlines() if line.strip())
    return items


def _seeker_text(profile):
    sections = []
    if profile.cv_file:
        cv_text = extract_text_from_cv(profile.cv_file)
        if cv_text.strip():
            sections.append(cv_text)
    for field in PROFILE_TEXT_FIELDS:
        value = (getattr(profile, field, '') or '').strip()
        if value:
            sections.append(value)
    return '\n\n'.join(sections)


def _seeker_skills(profile, job, candidate_text):
    skills = list(profile.skill_list)
    extracted = extract_skills_from_text(
        candidate_text,
        job=job,
        profile_skills=profile.skill_list,
    )
    seen = {skill.lower() for skill in skills}
    for skill in extracted:
        key = skill.lower()
        if key not in seen:
            seen.add(key)
            skills.append(skill)
    return skills


def _seeker_category_slug(profile):
    if getattr(profile, 'job_category_id', None):
        return profile.job_category.slug
    return (profile.category_slug or '').strip()


def _category_match_score(profile, job):
    if not job.category_id:
        return 50
    seeker_slug = _seeker_category_slug(profile)
    if not seeker_slug:
        return 0
    return 100 if seeker_slug == job.category.slug else 0


def compute_seeker_job_match(profile, job):
    """Return 0-100 match between a seeker profile and a job (engine score blended with category fit)."""
    from ats.matching_engine import score_candidate

    candidate_text = _seeker_text(profile)
    category_score = _category_match_score(profile, job)
    result = score_candidate(
        job,
        candidate_text,
        profile_skills=profile.skill_list,
        headline=profile.headline,
        profile_years=profile.years_experience,
        profile_qualification=profile.qualification,
    )
    if result['is_baseline']:
        return category_score if category_score == 100 else 0
    score = int(result['score'] * 0.8 + category_score * 0.2)
    return min(100, max(0, score))
