from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List

from fastapi import Request


@dataclass
class StoreData:
    id: int
    created_at: datetime
    store_name: str
    store_category: str | None = None
    store_region: str | None = None
    store_address: str | None = None
    store_phone_number: str | None = None
    store_info: str | None = None


@dataclass
class AttributeData:
    id: int
    attr_category: str
    attr_value: str
    created_at: datetime


@dataclass
class SongSampleData:
    id: int
    ai: str
    ai_model: str
    sample_song: str
    season: str | None = None
    num_of_people: int | None = None
    people_category: str | None = None
    genre: str | None = None


@dataclass
class PromptTemplateData:
    id: int
    prompt: str
    description: str | None = None


@dataclass
class SongFormData:
    store_name: str
    store_id: str
    prompts: str
    attributes: Dict[str, str] = field(default_factory=dict)
    attributes_str: str = ""
    lyrics_ids: List[int] = field(default_factory=list)
    llm_model: str = "gpt-5-mini"

    @classmethod
    async def from_form(cls, request: Request):
        """Request의 form 데이터로부터 dataclass 인스턴스 생성"""
        form_data = await request.form()

        # 고정 필드명들
        fixed_keys = {"store_info_name", "store_id", "llm_model", "prompts"}

        # lyrics-{id} 형태의 모든 키를 찾아서 ID 추출
        lyrics_ids = []
        attributes = {}

        for key, value in form_data.items():
            if key.startswith("lyrics-"):
                lyrics_id = key.split("-")[1]
                lyrics_ids.append(int(lyrics_id))
            elif key not in fixed_keys:
                attributes[key] = value

        # attributes를 문자열로 변환
        attributes_str = (
            "\r\n\r\n".join([f"{key} : {value}" for key, value in attributes.items()])
            if attributes
            else ""
        )

        return cls(
            store_name=form_data.get("store_info_name", ""),
            store_id=form_data.get("store_id", ""),
            attributes=attributes,
            attributes_str=attributes_str,
            lyrics_ids=lyrics_ids,
            llm_model=form_data.get("llm_model", "gpt-5-mini"),
            prompts=form_data.get("prompts", ""),
        )
