from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.security import get_password_hash
from app.models.user import Subject, SystemSettings, User

DEFAULT_SUBJECTS = [
    "语文",
    "数学",
    "英语",
    "物理",
    "化学",
    "生物",
    "历史",
    "地理",
    "政治",
]


def seed_subjects(db: Session) -> None:
    existing = {s.name for s in db.query(Subject).all()}
    for name in DEFAULT_SUBJECTS:
        if name not in existing:
            db.add(Subject(name=name))
    db.commit()


def seed_admin_and_settings(db: Session) -> None:
    row = db.get(SystemSettings, 1)
    if row is None:
        db.add(
            SystemSettings(
                id=1,
                registration_enabled=True,
                ai_provider="ollama",
                ollama_base_url=settings.OLLAMA_BASE_URL,
                ollama_model=settings.OLLAMA_MODEL,
                openai_base_url=settings.OPENAI_BASE_URL,
                openai_model=settings.OPENAI_MODEL,
                ocr_service_url=settings.OCR_SERVICE_URL or None,
            )
        )
    else:
        if not row.ollama_base_url:
            row.ollama_base_url = settings.OLLAMA_BASE_URL
        if not row.ollama_model:
            row.ollama_model = settings.OLLAMA_MODEL
        if not row.openai_base_url:
            row.openai_base_url = settings.OPENAI_BASE_URL
        if not row.openai_model:
            row.openai_model = settings.OPENAI_MODEL
        if not row.ocr_service_url and settings.OCR_SERVICE_URL:
            row.ocr_service_url = settings.OCR_SERVICE_URL
        if not row.ai_provider:
            row.ai_provider = "ollama"

    admin = db.query(User).filter(User.username == settings.ADMIN_DEFAULT_USERNAME).first()
    if admin is None:
        db.add(
            User(
                username=settings.ADMIN_DEFAULT_USERNAME,
                password_hash=get_password_hash(settings.ADMIN_DEFAULT_PASSWORD),
                is_superuser=True,
            )
        )
    elif not admin.is_superuser:
        admin.is_superuser = True

    db.commit()
