from qdrant_client import QdrantClient
from qdrant_client.models import Filter, SearchParams, PointStruct, FieldCondition, MatchValue
from typing import Optional, Dict, Any


class QdrantSearchService:
    def __init__(self):
        self.client = QdrantClient(url="http://localhost:6333")
        self.collection = "resumes"

    def search(self, vector, top_k=50, country_filter=None):
        """Search resumes with optional country filter"""
        search_filter = None
        if country_filter:
            search_filter = Filter(
                must=[
                    FieldCondition(
                        key="country_header_code",
                        match=MatchValue(value=country_filter)
                    )
                ]
            )
        
        hits = self.client.search(
            collection_name=self.collection, 
            query_vector=vector, 
            limit=top_k,
            query_filter=search_filter
        )

        return [
            {"resume_id": hit.payload["resume_id"], "vector_score": hit.score}
            for hit in hits
        ]
    
    def upsert_resume(self, jobseeker_id: str, vector: list, country_name: str = "", country_header_code: str = ""):
        """Store or update resume vector with metadata including country info"""
        try:
            point = PointStruct(
                id=int(jobseeker_id),
                vector=vector,
                payload={
                    "resume_id": jobseeker_id,
                    "country_name": country_name,
                    "country_header_code": country_header_code
                }
            )
            
            self.client.upsert(
                collection_name=self.collection,
                points=[point]
            )
            
            return True
        except Exception as e:
            print(f"Error upserting resume to Qdrant: {str(e)}")
            return False
