
from __future__ import annotations
from dataclasses import dataclass, asdict
from pathlib import Path
import json
import hashlib
import secrets
from datetime import datetime

DEMO_FREE_CHECKS = 3


@dataclass
class UserProfile:
    login: str
    full_name: str
    phone: str
    email: str
    password_hash: str
    salt: str
    paid: bool = False
    checks_used: int = 0
    created_at: str = ''


def hash_password(password: str, salt: str) -> str:
    return hashlib.sha256((salt + ':' + password).encode('utf-8')).hexdigest()


def create_profile(login: str, password: str, full_name: str, phone: str, email: str, paid: bool = False) -> UserProfile:
    salt = secrets.token_hex(16)
    return UserProfile(login=login, full_name=full_name, phone=phone, email=email, salt=salt, password_hash=hash_password(password, salt), paid=paid, created_at=datetime.utcnow().isoformat())


def load_profile(path) -> UserProfile | None:
    p = Path(path)
    if not p.exists():
        return None
    data = json.loads(p.read_text(encoding='utf-8'))
    return UserProfile(**data)


def save_profile(profile: UserProfile, path):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_text(json.dumps(asdict(profile), ensure_ascii=False, indent=2), encoding='utf-8')


def verify(profile: UserProfile, password: str) -> bool:
    return profile.password_hash == hash_password(password, profile.salt)


def may_run_check(profile: UserProfile | None, demo_mode: bool = True) -> bool:
    if profile and profile.paid:
        return True
    if not demo_mode:
        return True
    used = profile.checks_used if profile else 0
    return used < DEMO_FREE_CHECKS


def may_export_checklist(profile: UserProfile | None, paid_flag: bool = False) -> bool:
    return bool(paid_flag or (profile and profile.paid))


def register_check(profile: UserProfile | None, profile_path=None):
    if profile:
        profile.checks_used += 1
        if profile_path:
            save_profile(profile, profile_path)
