"""Helpers for job application method selection and CV handling."""
from __future__ import annotations

import os

from django.core.files.base import ContentFile

from jobs.models import Job


def normalize_application_methods(methods) -> list[str]:
    valid = {choice.value for choice in Job.ApplicationMethod}
    if not methods:
        return []
    return [method for method in methods if method in valid]


def application_methods_for_job(job) -> list[str]:
    stored = normalize_application_methods(getattr(job, 'application_methods', None) or [])
    if stored:
        return stored
    legacy = getattr(job, 'application_method', None)
    if legacy in {Job.ApplicationMethod.PEZAJOB, Job.ApplicationMethod.EXTERNAL}:
        return [legacy]
    return [Job.ApplicationMethod.EXTERNAL]


def profile_cv_filename(profile) -> str:
    if not profile or not profile.cv_file:
        return ''
    return os.path.basename(profile.cv_file.name)


def seeker_has_profile_cv(profile) -> bool:
    return bool(profile and profile.cv_file and profile.cv_file.name)


def attach_profile_cv(application, profile=None) -> bool:
    """Copy the seeker's profile CV onto the application when none was uploaded."""
    if application.cv_file:
        return False
    if profile is None:
        profile = getattr(application.applicant, 'seeker_profile', None)
    if not seeker_has_profile_cv(profile):
        return False
    filename = profile_cv_filename(profile)
    with profile.cv_file.open('rb') as src:
        application.cv_file.save(filename, ContentFile(src.read()), save=False)
    return True
