from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr, validator
from fastapi.middleware.cors import CORSMiddleware
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
from typing import Optional

app = FastAPI()

# CORS 설정
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ContactForm(BaseModel):
    name: str
    email: EmailStr
    company: str
    message: str
    
    @validator('name')
    def name_not_empty(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Full Name is required')
        return v.strip()
    
    @validator('company')
    def company_not_empty(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Company Name is required')
        return v.strip()
    
    @validator('message')
    def message_valid(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Project description is required')
        if len(v) > 5000:
            raise ValueError('Message is too long (max 5000 characters)')
        return v.strip()

@app.post("/api/contact")
async def send_contact_email(form: ContactForm):
    """Contact form email handler"""
    try:
        # SMTP 설정 - mailcow Postfix 서버
        # Docker 네트워크 내에서는 서비스 이름으로 접근
        smtp_server = "mailcowdockerized_postfix-mailcow_1"
        smtp_port = 25
        
        print(f"Attempting to connect to SMTP: {smtp_server}:{smtp_port}")
        
        # 메시지 구성
        msg = MIMEMultipart('alternative')
        msg['Subject'] = f"[Contact Form] {form.name} - {form.company}"
        msg['From'] = "contact@hanmocnn.co.kr"
        msg['To'] = "windpacer@hanmocnn.co.kr"
        msg['Reply-To'] = form.email
        
        # 텍스트 본문
        text_body = f"""
New contact form submission:

Name: {form.name}
Email: {form.email}
Company: {form.company}
Message:
{form.message}

---
Submitted from Hanmo Contact Form
"""
        
        # HTML 본문
        html_body = f"""
<html>
  <body>
    <h3>New contact form submission:</h3>
    <p><strong>Name:</strong> {form.name}</p>
    <p><strong>Email:</strong> {form.email}</p>
    <p><strong>Company:</strong> {form.company}</p>
    <p><strong>Message:</strong></p>
    <pre>{form.message}</pre>
    <hr>
    <p><em>Submitted from Hanmo Contact Form</em></p>
  </body>
</html>
"""
        
        part1 = MIMEText(text_body, 'plain')
        part2 = MIMEText(html_body, 'html')
        msg.attach(part1)
        msg.attach(part2)
        
        # SMTP 연결 및 메일 전송
        print(f"Connecting to SMTP server...")
        with smtplib.SMTP(smtp_server, smtp_port, timeout=10) as server:
            print(f"Connected! Sending email...")
            server.sendmail(
                "contact@hanmocnn.co.kr",
                "windpacer@hanmocnn.co.kr",
                msg.as_string()
            )
            print(f"Email sent successfully!")
        
        return {
            "success": True,
            "message": "Your message has been sent successfully. We will get back to you soon."
        }
        
        return {
            "success": True,
            "message": "Your message has been sent successfully. We will get back to you soon."
        }
    
    except Exception as e:
        import traceback
        print(f"Error sending email: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(
            status_code=500,
            detail="Failed to send email. Please try again later."
        )

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "ok"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001)
