from claims.models import ClaimDraft
from claims.services.ai_assistant import (
    AIAssistantError,
    apply_payload_to_draft,
    generate_draft_payload,
)
from claims.services.article_fetcher import ArticleFetchError, fetch_article_text


def process_claim_draft(draft, *, refinement=''):
    draft.error_message = ''
    draft.status = ClaimDraft.DraftStatus.PROCESSING
    draft.save(update_fields=['error_message', 'status', 'updated_at'])

    user_message_parts = []
    if draft.article_url:
        user_message_parts.append(f'Link: {draft.article_url}')
    if draft.user_notes:
        user_message_parts.append(draft.user_notes)
    if draft.uploaded_file:
        user_message_parts.append(f'Datei: {draft.uploaded_file.name}')
    if refinement:
        user_message_parts.append(f'Überarbeitung: {refinement}')

    draft.add_message('user', '\n'.join(user_message_parts) or 'Neuer Entwurf')
    draft.save(update_fields=['conversation', 'updated_at'])

    try:
        article_text = draft.article_text
        if draft.article_url and not refinement:
            article_text = fetch_article_text(draft.article_url)
            draft.article_text = article_text
            draft.save(update_fields=['article_text', 'updated_at'])

        payload = generate_draft_payload(
            article_url=draft.article_url,
            article_text=article_text,
            user_notes=draft.user_notes,
            uploaded_file=draft.uploaded_file if draft.uploaded_file else None,
            refinement=refinement,
            previous_payload=draft.ai_raw_response if refinement else None,
        )
        apply_payload_to_draft(draft, payload)
        draft.status = ClaimDraft.DraftStatus.REVIEW
        draft.save()
        return draft
    except (ArticleFetchError, AIAssistantError) as exc:
        draft.status = ClaimDraft.DraftStatus.FAILED
        draft.error_message = str(exc)
        draft.add_message('assistant', f'Fehler: {exc}')
        draft.save()
        raise
