import sys
import json
import smtplib
import datetime
import requests
from pathlib import Path
from numbers import Real
from email.message import EmailMessage
from jinja2 import Environment, FileSystemLoader, select_autoescape
    
# Load your real config before calling any API
GLOBAL_CONFIG_PATH = "config.json"
try:
    with open(GLOBAL_CONFIG_PATH, "r", encoding="utf-8") as f:
        config = json.load(f)
except Exception as e:
    print(f"Failed to load config: {e}")
    sys.exit(1)

WEB_CONFIG = config.get("WEB", {})
WEB_BASE_URL = WEB_CONFIG.get("BASE_URL")

API_CONFIG = config.get("API", {})
BASE_URL = API_CONFIG.get("BASE_URL")

SMPT_CONFIG = config.get("SMPT", {})
SMPTSERVER = SMPT_CONFIG.get("SMPTSERVER")
PORT = SMPT_CONFIG.get("PORT")
SENDER_EMAIL = SMPT_CONFIG.get("SENDER_EMAIL")
SENDER_PASSWORD = SMPT_CONFIG.get("SENDER_PASSWORD")
RECIPIENT_EMAILS = SMPT_CONFIG.get("RECIPIENT_EMAILS")

UNIQUE_IDENTIFIER_CONFIG = config.get("UNIQUE_IDENTIFIER", {})
PROJECT_IDS = UNIQUE_IDENTIFIER_CONFIG.get("PROJECT_IDS")


def render_template_from_file(template_name,context):
    base_dir = Path(__file__).parent
    env = Environment(
        loader=FileSystemLoader(searchpath=str(base_dir)),
        autoescape=select_autoescape(["html", "xml"])
    )
    tmpl = env.get_template(template_name)
    return tmpl.render(**context)

def fetch_Project_report(project_id):
    headers = {"Content-Type": "application/json"}
    try:
        response = requests.get(f"{BASE_URL}/market/get/project/report/{project_id}", headers=headers)
        response.raise_for_status()
        data = response.json()["data"]
        print(f"Project report for project \"{data["projectName"]}\" fetched successfully.")
        return data
    except Exception as e:
        print(f"Select tenant error: {e}")
        return None
    
def get_percentage(part, whole, decimals: int = 2):
    if not isinstance(part, Real) or not isinstance(whole, Real):
        raise TypeError("part and whole must be numbers")
    if whole == 0:
        return 0.0
    return round((part / whole) * 100.0, decimals)

def value_minization(minimize_value):
    if minimize_value >= 1000:
        minimized_value = round((minimize_value/1000),2)
        result = f"{minimized_value}K"
    else:
        result = f"{minimize_value}"
    return result

if __name__ == "__main__":
    template_name = "dpr.html"
    project_ids = [p.strip() for p in PROJECT_IDS.split(",") if p.strip()]

    for project_id in project_ids:

        data = fetch_Project_report(project_id)
        if "attendancePercentage" in data:
            attendance_percentage = data["attendancePercentage"]
        else:
            attendance_percentage = get_percentage(data["todaysAttendances"], data["totalEmployees"], 2)
        
        if "taskPercentage" in data:
            task_percentage = data["taskPercentage"]
        else:
            task_percentage = get_percentage(data["totalCompletedTask"], data["totalPlannedTask"], 2)

        if "todaysCompletedTasks" in data:
            todays_completed_tasks = data["todaysCompletedTasks"]
        else:
            todays_completed_tasks = 0

        web_url = f"{WEB_BASE_URL}/auth/login"

        dt = datetime.datetime.strptime(data["date"], "%Y-%m-%dT%H:%M:%SZ")
        api_formatted_date = dt.strftime("%d-%b-%Y")

        total_planned_work = value_minization(data["totalPlannedWork"])
        total_completed_work = value_minization(data["totalCompletedWork"])
        total_planned_task = value_minization(data["totalPlannedTask"])
        total_completed_task = value_minization(data["totalCompletedTask"])

        context = {
            "webUrl":web_url,
            "date": api_formatted_date,
            "projectName": data["projectName"],
            "timeStamp": data["timeStamp"],
            "todaysAttendances": data["todaysAttendances"],
            "totalEmployees": data["totalEmployees"],
            "attendancePercentage":attendance_percentage,
            "taskPercentage":task_percentage,
            "regularizationPending": data["regularizationPending"],
            "checkoutPending": data["checkoutPending"],
            "totalPlannedWork": total_planned_work,
            "totalCompletedWork": total_completed_work,
            "totalPlannedTask": total_planned_task,
            "totalCompletedTask": total_completed_task,
            "completionStatus": round(data["completionStatus"],2),
            "reportPending": data["reportPending"],
            "todaysAssignTasks": data["todaysAssignTasks"],
            "todaysCompletedTasks": todays_completed_tasks,
            "websiteName":"OnFieldWork.com",
            "teamOnSite": data["teamOnSite"],
            "performedTasks": data["performedTasks"],
            "performedAttendance": data["performedAttendance"]
        }

        # print(context)
        project_name = data["projectName"]
        html = render_template_from_file(template_name,context)

        # print(html)

        msg = EmailMessage()
        msg["Subject"] = f"DPR - {api_formatted_date} - {project_name}"
        msg["From"] = SENDER_EMAIL
        msg["To"] = RECIPIENT_EMAILS
        msg.set_content("HTML version attached as alternative.")
        msg.add_alternative(html, subtype="html")

        with smtplib.SMTP(SMPTSERVER, PORT) as smtp:
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo()
                smtp.login(SENDER_EMAIL, SENDER_PASSWORD)
                smtp.send_message(msg)
