import sys
import random
from sqlalchemy.orm import Session
from app.database import SessionLocal, engine
from app.models.recruitment import Recruitment
from app.models.company import Company
from app.models.user import User

def create_jd(title_arg=None):
    db: Session = SessionLocal()
    try:
        # 1. 회사 찾기 (첫 번째 회사 사용)
        company = db.query(Company).first()
        if not company:
            print("[ERROR] No company found. Please run 'create_admin.py' first.")
            return

        # 2. 샘플 JD 리스트
        samples = [
            {
                "title": "백엔드 개발자 (Python/Django)",
                "description": """
                [주요 업무]
                - 대규모 트래픽 처리를 위한 서버 아키텍처 설계
                - RESTful API 설계 및 개발
                - 데이터베이스 모델링 및 최적화
                """,
                "requirements": """
                - Python, Django/FastAPI 개발 경력 3년 이상
                - AWS, Docker, Kubernetes 활용 가능하신 분
                - RDBMS (MySQL, PostgreSQL) 및 NoSQL 경험
                """
            },
            {
                "title": "프론트엔드 리드 개발자 (React)",
                "description": """
                [주요 업무]
                - 프론트엔드 아키텍처 설계 및 기술 리딩
                - UI/UX 고도화 및 성능 최적화
                - 디자인 시스템 구축 및 운영
                """,
                "requirements": """
                - React.js, TypeScript 숙련자
                - Next.js 등 SSR 프레임워크 경험
                - 웹 성능 최적화 및 접근성 개선 경험
                """
            },
            {
                "title": "AI/ML 리서치 엔지니어",
                "description": """
                [주요 업무]
                - LLM 기반 서비스 모델 연구 및 개발
                - 추천 시스템 알고리즘 개선
                - 데이터 전처리 파이프라인 구축
                """,
                "requirements": """
                - PyTorch, TensorFlow 등 딥러닝 프레임워크 능숙
                - NLP(자연어 처리) 관련 프로젝트 경험
                - 최신 논문 구현 및 적용 능력
                """
            }
        ]

        # 3. 선택 (인자 없으면 랜덤)
        if title_arg:
            target = {
                "title": title_arg,
                "description": "[Custom JD] Generated by script.",
                "requirements": "Custom requirements."
            }
        else:
            target = random.choice(samples)

        print(f"[INFO] Creating Recruitment: {target['title']}...")

        jd = Recruitment(
            company_id=company.id,
            title=target['title'],
            description=target['description'] + "\n\n" + target['requirements'], # description에 합쳐서 저장
            requirements=target['requirements'] # 별도로도 저장
        )
        db.add(jd)
        db.commit()
        db.refresh(jd)
        
        print(f"[SUCCESS] JD Created! (ID: {jd.id})")

    except Exception as e:
        print(f"[ERROR] Failed to create JD: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    title_input = sys.argv[1] if len(sys.argv) > 1 else None
    create_jd(title_input)
