from fastapi import FastAPI, APIRouter, Depends, Request, HTTPException, Form
from datetime import datetime
from dotenv import load_dotenv
import os


from fastapi.responses import HTMLResponse
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select





from pydantic import BaseModel, HttpUrl
from urllib.parse import urlparse, parse_qs
from linkedin_api import Linkedin
import logging
from utils.logging_setup import configure_global_logging

load_dotenv()
# # Ваши учетные данные LinkedIn


configure_global_logging()

router = APIRouter()


username = os.getenv('USERNAME')
password = os.getenv('PASSWD')
api = Linkedin(username, password)


DATABASE_URL = os.getenv('DATABASE_URL')  # Ваши параметры подключения
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)



    
class UrlModel(BaseModel):
    link_profile: HttpUrl  # Используем HttpUrl для проверки валидности URL


async def get_session() -> AsyncSession:
    async with async_session() as session:
        yield session



@router.post("/link_vacancy")
async def vacancy_url(data: UrlModel):
    if not str(data.link_profile).startswith("https://www.linkedin.com/"):
        # Возвращаем исключение с кодом 400 и сообщением об ошибке
        raise HTTPException(status_code=400, detail="Неправильная ссылка")
    
    query_params = parse_qs(urlparse(str(data.link_profile)).query)
    current_job_id = query_params.get("currentJobId", [None])[0]

    jobs = api.get_job(current_job_id)
    location = jobs['formattedLocation'] 
    title = jobs['title']
    listedAt = jobs['listedAt']
    
    # Преобразование из миллисекунд в секунды и конвертация
    future_date = datetime.fromtimestamp(listedAt / 1000)

    # Текущая дата
    current_date = datetime.now()

    # Разница в днях
    difference = abs((future_date - current_date).days)

    # print(f"Разница в днях: {difference}")
    
    
    jobPostingId = jobs['jobPostingId']
    # workplaceTypesResolutionResults = jobs['workplaceTypesResolutionResults']
    
    
    
    # Извлекаем все localizedName
    # localized_names = [value['localizedName'] for value in workplaceTypesResolutionResults.values()]

    # print(localized_names)

    # localized_name = workplaceTypesResolutionResults['urn:li:fs_workplaceType:2']['localizedName']
    link = f'https://www.linkedin.com/jobs/view/{current_job_id}/'
    

    return {"job_id": current_job_id,
            "job_title": title,
            "minimum_annual_salary": f"minimum_annual_salary",
            "salary_currency": 'salary_currency',
            'location_type': "location_type",
            'location': location,
            "job_level": "job_level",
            "job_type": 'job_type',
            "days_posted": difference,
            "hourly_rate": "hourly_rate", 
            "link": link}